@a2f0/agent-tool 0.1.74 → 0.1.76
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/package.json +1 -1
- package/skills/optimize-ci/SKILL.md +117 -0
- package/skills/optimize-ci/agents/openai.yaml +4 -0
- package/skills/optimize-ci/references/lessons.md +81 -0
- package/src/ci/command.ts +98 -0
- package/src/ci/timings.ts +181 -0
- package/src/cli.ts +9 -1
- package/src/permissions/catalog.ts +1 -1
- package/src/skills/bundled.ts +5 -0
package/package.json
CHANGED
|
@@ -0,0 +1,117 @@
|
|
|
1
|
+
---
|
|
2
|
+
name: optimize-ci
|
|
3
|
+
description: Cut a repository's CI wall-clock time in measured rounds - find the job that holds the critical path across recent runs, then split, parallelize, cache, or gate it without checking less, shipping each change through ship-pr. Use when the user asks to speed up CI, a pipeline, or required checks; not for making individual tests faster, production performance, or page loads (performance-pass).
|
|
4
|
+
---
|
|
5
|
+
|
|
6
|
+
# Optimize CI
|
|
7
|
+
|
|
8
|
+
A CI pass makes developers wait less for the same verdict. Every test, check,
|
|
9
|
+
and required job that ran before still runs; what changes is where and when it
|
|
10
|
+
runs and what is reused. A faster pipeline that checks less is a regression,
|
|
11
|
+
not a win.
|
|
12
|
+
|
|
13
|
+
## Measuring
|
|
14
|
+
|
|
15
|
+
`agent-tool ci timings` reads GitHub Actions through `gh` and changes nothing.
|
|
16
|
+
When a repository's agent-tool pin predates the command, run
|
|
17
|
+
`bunx --bun @a2f0/agent-tool@latest ci timings`.
|
|
18
|
+
|
|
19
|
+
| Command | Shows |
|
|
20
|
+
| --- | --- |
|
|
21
|
+
| `ci timings --workflow <file> --gate <job> [--event pull_request] [--limit 80]` | Over the latest successful first-attempt runs: wall clock (median, p90), the lane that finished last in each run, and every job's duration, how often it took at least `--threshold` minutes (did real work rather than replay a cache), and how long it waited to start |
|
|
22
|
+
| `ci timings --run <id>` | One run's jobs, longest first, with their steps |
|
|
23
|
+
| `ci timings --job <id>` | One job's log: which Turbo tasks executed and which replayed from cache, and Bun test files ranked by summed case time |
|
|
24
|
+
|
|
25
|
+
A lane is a job name without shard counters, so `Test (api 1/3)` and
|
|
26
|
+
`Test (api 2/3)` both count as `Test (api)`.
|
|
27
|
+
|
|
28
|
+
## Procedure
|
|
29
|
+
|
|
30
|
+
1. Scope. Read the repository's guidance and CI policy: required checks, any
|
|
31
|
+
aggregate gate job, path filters, cache bridges, and merge rules. The target
|
|
32
|
+
is the wall clock developers wait on: the median and p90 of pull-request
|
|
33
|
+
runs, measured to the gate job.
|
|
34
|
+
2. Baseline. Run `ci timings` over 50 to 80 runs, pull requests and the default
|
|
35
|
+
branch separately. Record wall median and p90, `lastToFinish`, the top jobs'
|
|
36
|
+
medians, and `overThresholdShare`. A scheduled uncached run, where the
|
|
37
|
+
repository has one, shows each job's cost without cache replay.
|
|
38
|
+
3. Find the critical path. The lane that finishes last in most runs is the
|
|
39
|
+
target; break it down with `--run` (which step) and `--job` (which task or
|
|
40
|
+
test file). Then name the next two or three lanes: removing the first exposes
|
|
41
|
+
them, so plan a round that brings all of them under the target.
|
|
42
|
+
4. Choose levers, safest first:
|
|
43
|
+
- Split serial work across runners. A long suite hidden in a catch-all job
|
|
44
|
+
sets that job's length; give it its own matrix entries. Balance shards by
|
|
45
|
+
measured time, not file count (Bun's `--shard` with `--timings`,
|
|
46
|
+
Playwright's `--shard` from spec durations): a count split of uneven files
|
|
47
|
+
is lopsided. No shard is shorter than its longest file, so split that file
|
|
48
|
+
when its cases are independent.
|
|
49
|
+
- Use the cores the runner has. Check effective parallelism: test runners'
|
|
50
|
+
CI defaults (Playwright uses half the cores), tool flags (TLC
|
|
51
|
+
`-workers 1`), and pool sizes. Raise them only with measured memory
|
|
52
|
+
headroom, and keep timing-sensitive end-to-end suites on their own runners
|
|
53
|
+
rather than crowding one.
|
|
54
|
+
- Schedule longest first in any pool, so a long item never starts last.
|
|
55
|
+
- Cache what every run rebuilds: toolchains, browsers, package stores,
|
|
56
|
+
compiler output (Xcode DerivedData and SwiftPM, Gradle), and task results.
|
|
57
|
+
Key each cache on exactly what its output depends on.
|
|
58
|
+
- Keep cache keys and path filters narrow. A file every pull request touches
|
|
59
|
+
(a lockfile that version bumps rewrite, version fields, embedded build
|
|
60
|
+
versions) silently defeats both. A job with a high `overThresholdShare`
|
|
61
|
+
that should usually be cached points to one.
|
|
62
|
+
- Remove duplicate work, such as one task in two jobs racing to fill the
|
|
63
|
+
same cache entry.
|
|
64
|
+
- Never delete or skip tests, loosen assertions or timeouts, drop a backend,
|
|
65
|
+
make a required check optional, or let a cache hit stand in for a check
|
|
66
|
+
whose inputs it does not cover.
|
|
67
|
+
5. Prove each change. Ship one lever per PR with `ship-pr`. A task cache can
|
|
68
|
+
hide the change, so measure on a run that executes the lane: changed task
|
|
69
|
+
arguments or inputs miss on their own; otherwise dispatch an uncached run.
|
|
70
|
+
Give baseline and after numbers with run ids in the PR body. Keep a policy
|
|
71
|
+
test beside the workflow that fails when a shard or gated job goes missing.
|
|
72
|
+
6. Re-measure after merging, with the same command over runs created after the
|
|
73
|
+
merge, and report the change in median and p90 wall clock. Start the next
|
|
74
|
+
round from step 3 with the new top lane.
|
|
75
|
+
7. Learn. Repository-specific findings go in that repository's guidance.
|
|
76
|
+
Cross-repository lessons go in agent-tool's
|
|
77
|
+
`skills/optimize-ci/references/lessons.md` by PR, naming the repository and
|
|
78
|
+
PR; [the installed copy](references/lessons.md) is read-only.
|
|
79
|
+
|
|
80
|
+
## Pitfalls
|
|
81
|
+
|
|
82
|
+
- GitHub Actions caches are scoped. A pull request reads entries from its own
|
|
83
|
+
ref and the default branch, never another pull request's, and one that starts
|
|
84
|
+
before the default branch's run finishes misses the entries that run is still
|
|
85
|
+
writing. Check timing before calling a miss a key bug.
|
|
86
|
+
- Turbo and Nx hash task arguments, so shards cache independently only when the
|
|
87
|
+
shard argument reaches the task.
|
|
88
|
+
- A cached job still costs a runner, its setup, and a concurrency slot.
|
|
89
|
+
Account limits, macOS especially, queue jobs as shards multiply: compare
|
|
90
|
+
`startLagSeconds` p90 before and after, and let path filters skip lanes a
|
|
91
|
+
change cannot affect.
|
|
92
|
+
- A re-run attempt mixes timestamps from several attempts; `ci timings` leaves
|
|
93
|
+
re-runs out, and manual analysis should too.
|
|
94
|
+
- Turbo buffers a task's output until it ends, so log timestamps show
|
|
95
|
+
completion, not progress. Use the test runner's own case durations.
|
|
96
|
+
- Turning a job into a matrix renames its check (`Web E2E` becomes
|
|
97
|
+
`Web E2E (1/3)`). Update branch protection, rulesets, and the merge helper's
|
|
98
|
+
required checks together, or require an aggregate gate job instead.
|
|
99
|
+
- Changing a shard count reshuffles which files share a worker; with test
|
|
100
|
+
isolation off, that can surface leaks between files. Run every new shard
|
|
101
|
+
composition before pushing.
|
|
102
|
+
- Config chosen on `CI` (reporters, plugins, entries) looks different to
|
|
103
|
+
static analysis locally and on CI, so a check passes locally and fails on CI.
|
|
104
|
+
Keep config the same everywhere, or run those checks with `CI=true` too.
|
|
105
|
+
- A recorded-durations file only orders and balances work. It must ignore
|
|
106
|
+
entries for items that no longer exist and weight unknown ones, or a rename
|
|
107
|
+
in any pull request fails CI on a scheduling hint.
|
|
108
|
+
- Merge policy is part of the wall clock: a check that forces queued pull
|
|
109
|
+
requests to integrate after every merge reruns their CI one at a time.
|
|
110
|
+
|
|
111
|
+
## Ownership
|
|
112
|
+
|
|
113
|
+
agent-tool (`a2f0/agent-tool`) owns this skill at `skills/optimize-ci/` and the
|
|
114
|
+
`ci timings` command at `src/ci/`, with its tests beside it; `agent-tool skills
|
|
115
|
+
install --apply` installs it in each adopting repository. Change it there,
|
|
116
|
+
never in an installed copy. A repository's CI layout, required checks, and
|
|
117
|
+
measured baselines belong in its own docs.
|
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
interface:
|
|
2
|
+
display_name: "Optimize CI"
|
|
3
|
+
short_description: "Cut CI wall-clock time in measured rounds without checking less"
|
|
4
|
+
default_prompt: "Use $optimize-ci to make this repository's CI faster: measure which job holds the wall clock, change one lever, prove it on CI, and ship."
|
|
@@ -0,0 +1,81 @@
|
|
|
1
|
+
# CI lessons
|
|
2
|
+
|
|
3
|
+
Cross-repository findings from CI passes, newest first. Each names the
|
|
4
|
+
repository and the PRs it came from; recheck before relying on one.
|
|
5
|
+
|
|
6
|
+
## Split the long serial file list out of a catch-all job
|
|
7
|
+
|
|
8
|
+
a2f0/tearleads #3333. A job running "the remaining package tests" finished
|
|
9
|
+
last in 60 of 80 runs (median 18.6 minutes): one package's end-to-end suite ran
|
|
10
|
+
1158 s of serial files inside it. Giving that package five matrix shards,
|
|
11
|
+
balanced with Bun's `--timings` from per-file times read out of uncached job
|
|
12
|
+
logs, took the catch-all job from 20.9 to 7.4 minutes and the whole uncached
|
|
13
|
+
run from 21 to 14. The slowest shard came in about 25% over its prediction;
|
|
14
|
+
plan shard counts with that margin. Bun keeps files in path order within a
|
|
15
|
+
timed shard, so a long file only splits usefully at higher shard counts, and
|
|
16
|
+
no shard is shorter than its longest file.
|
|
17
|
+
|
|
18
|
+
## Playwright shards by test count, not time
|
|
19
|
+
|
|
20
|
+
a2f0/tearleads #3332. Playwright 1.64 deals whole spec files to shards by test
|
|
21
|
+
count in project-then-file order, so a shard full of fast tests finishes early:
|
|
22
|
+
three shards left the slowest with 46% of the suite, four with 33%. Four
|
|
23
|
+
shards took the browser suite from a 13.1 minute median to about 6 minutes.
|
|
24
|
+
`playwright test --list --shard=i/N --reporter=json` names each shard's exact
|
|
25
|
+
tests before any build, so a shard can install only the browsers its projects
|
|
26
|
+
use (63 s to 23 s for Chromium-only shards). The same shard's time varied from
|
|
27
|
+
2.9 to 4.7 minutes with identical inputs: read the slowest shard as a range.
|
|
28
|
+
|
|
29
|
+
## Environment-conditional config splits local and CI static analysis
|
|
30
|
+
|
|
31
|
+
a2f0/tearleads #3332. A Playwright config that added a reporter only when `CI`
|
|
32
|
+
was set let Knip's Playwright plugin see the reporter on CI but not locally, so
|
|
33
|
+
Knip passed locally and failed on CI with a redundant-entry hint. Keep config
|
|
34
|
+
the same in every environment, or run static checks with `CI=true` as well.
|
|
35
|
+
|
|
36
|
+
## Version bumps and lockfiles defeat path filters and task keys
|
|
37
|
+
|
|
38
|
+
a2f0/tearleads #3331 and #3334. Every pull request bumped package versions and
|
|
39
|
+
refreshed the lockfile, so lanes meant only for native or infrastructure
|
|
40
|
+
changes ran in 72 to 74 of 80 runs. Two fixes helped:
|
|
41
|
+
|
|
42
|
+
- Treat a lockfile diff that changes only workspace `version` fields as
|
|
43
|
+
touching nothing, and count anything unparseable as changed.
|
|
44
|
+
- Key a task on exactly what it reads. An iOS compile check that synced a
|
|
45
|
+
placeholder page instead of the web build, and moved from a root task to a
|
|
46
|
+
package task, cut its key changes from 277 to 18 per 300 merges, and its
|
|
47
|
+
job from 12.5 minutes to a 30 s replay.
|
|
48
|
+
|
|
49
|
+
In Turbo, a root (`//#`) task always hashes the root `package.json`, and a
|
|
50
|
+
package task with explicit inputs always hashes its own manifest. Keep the
|
|
51
|
+
manifest in a native key when the sync tool runs manifest hook scripts, as
|
|
52
|
+
`cap sync` does.
|
|
53
|
+
|
|
54
|
+
## Prove a build cache with a warm run before keeping it
|
|
55
|
+
|
|
56
|
+
a2f0/tearleads #3334. An exact-key Xcode DerivedData restore on the runner's
|
|
57
|
+
Xcode 16.4 still rebuilt all 1622 object files: 690 MB of cache for no gain,
|
|
58
|
+
while the same restore on a newer local Xcode cut 190 s to 31 s. Measure a
|
|
59
|
+
cold run that saves and a warm run that restores before shipping any cache.
|
|
60
|
+
|
|
61
|
+
## More workers on the same cores is not a split
|
|
62
|
+
|
|
63
|
+
a2f0/tearleads #3335. Raising the TLC model checker from two to four JVMs at a
|
|
64
|
+
time on 4-vCPU runners made each run at least 1.5 times slower, so the job
|
|
65
|
+
fell only to the total work divided by four, and runner speed varied about
|
|
66
|
+
twofold between uncached runs on the default branch (491 to 1008 s): one run
|
|
67
|
+
could not show the change helped. Once total work bounds a job, split it
|
|
68
|
+
across runners, longest item first, and measure against many baseline runs.
|
|
69
|
+
A scheduling hint such as a recorded-durations file must ignore stale entries,
|
|
70
|
+
as Bun's `--timings` does: failing on a renamed item turns every rename
|
|
71
|
+
elsewhere into a CI failure.
|
|
72
|
+
|
|
73
|
+
## Merge policy can serialize a CI round
|
|
74
|
+
|
|
75
|
+
a2f0/tearleads, 2026-11-26. A version check that required each branch to carry
|
|
76
|
+
the default branch's version of every package made each merge force every
|
|
77
|
+
queued pull request to integrate and rerun its full CI, so five pull requests
|
|
78
|
+
merged one CI run at a time. A one-off push-gate break on the default branch
|
|
79
|
+
(stale ignore entries left by a merge) blocked every push until its repair
|
|
80
|
+
merged. Count merge-queue time in a round's estimate, and let the pull request
|
|
81
|
+
that repairs a shared gate merge first.
|
|
@@ -0,0 +1,98 @@
|
|
|
1
|
+
/** `agent-tool ci timings`: read-only GitHub Actions timing reports; CI_TIMINGS_USAGE lists the modes. */
|
|
2
|
+
import { writeSync } from "node:fs";
|
|
3
|
+
import { runRead } from "../git/prContext";
|
|
4
|
+
import { assert, json, option, output, repository } from "../workflows/core";
|
|
5
|
+
import { parseJobLog, runSteps, summarizeRuns, type TimedJob, type TimedRun } from "./timings";
|
|
6
|
+
|
|
7
|
+
export const CI_TIMINGS_USAGE = `Usage: agent-tool ci timings [--workflow <file|id>] [--branch <name>] [--event <event>] [--limit <n>] [--gate <job>] [--threshold <minutes>]
|
|
8
|
+
agent-tool ci timings --run <run-id> [--min-seconds <n>]
|
|
9
|
+
agent-tool ci timings --job <job-id> [--top <n>]
|
|
10
|
+
|
|
11
|
+
Without --run or --job, summarizes the latest successful first-attempt runs
|
|
12
|
+
(default 50, at most 200): wall clock, the lane that finished last, and each
|
|
13
|
+
job's duration, how often it took at least --threshold minutes (default 2),
|
|
14
|
+
and how long it waited to start. --run lists one run's jobs and their steps
|
|
15
|
+
of at least --min-seconds (default 10). --job reads one job's log: Turbo task
|
|
16
|
+
cache results and Bun test files ranked by summed case time (--top, default 25).
|
|
17
|
+
Prints JSON; reads GitHub through gh and changes nothing.`;
|
|
18
|
+
|
|
19
|
+
const JOB_FIELDS = "id, name, conclusion, startedAt: .started_at, completedAt: .completed_at";
|
|
20
|
+
const STEP_FIELDS = "steps: [(.steps // [])[] | {name, conclusion, startedAt: .started_at, completedAt: .completed_at}]";
|
|
21
|
+
|
|
22
|
+
function integer(value: string | undefined, name: string, fallback: number, min: number, max: number): number {
|
|
23
|
+
const parsed = value === undefined ? fallback : Number(value);
|
|
24
|
+
assert(Number.isSafeInteger(parsed) && parsed >= min && parsed <= max, `${name} must be an integer from ${min} to ${max}.`);
|
|
25
|
+
return parsed;
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
function id(value: string, name: string): string {
|
|
29
|
+
assert(/^\d+$/.test(value), `${name} must be a numeric id.`);
|
|
30
|
+
return value;
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
function jobs(repo: string, runId: number | string, steps: boolean): TimedJob[] {
|
|
34
|
+
const fields = steps ? `${JOB_FIELDS}, ${STEP_FIELDS}` : JOB_FIELDS;
|
|
35
|
+
return runRead("gh", ["api", "--paginate", `repos/${repo}/actions/runs/${runId}/jobs?per_page=100`, "--jq", `.jobs[] | {${fields}}`])
|
|
36
|
+
.split("\n").filter(Boolean).map(line => JSON.parse(line) as TimedJob);
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
/** Successful runs, newest first, a page of up to 100 at a time until `limit`; `read` is gh's JSON reader, replaced in tests. */
|
|
40
|
+
export function listRuns(repo: string, filters: { workflow?: string; branch?: string; event?: string }, limit: number, read: <T>(args: string[]) => T = json): Omit<TimedRun, "jobs">[] {
|
|
41
|
+
const base = filters.workflow ? `repos/${repo}/actions/workflows/${encodeURIComponent(filters.workflow)}/runs` : `repos/${repo}/actions/runs`;
|
|
42
|
+
const query = new URLSearchParams({ status: "success", per_page: String(Math.min(limit, 100)) });
|
|
43
|
+
if (filters.branch) query.set("branch", filters.branch);
|
|
44
|
+
if (filters.event) query.set("event", filters.event);
|
|
45
|
+
const runs: Omit<TimedRun, "jobs">[] = [];
|
|
46
|
+
for (let page = 1; runs.length < limit; page++) {
|
|
47
|
+
query.set("page", String(page));
|
|
48
|
+
const batch = read<Omit<TimedRun, "jobs">[]>(["api", `${base}?${query}`, "--jq", "[.workflow_runs[] | {id, event, attempt: .run_attempt, createdAt: .created_at}]"]);
|
|
49
|
+
assert(Array.isArray(batch), "Could not list workflow runs.");
|
|
50
|
+
runs.push(...batch);
|
|
51
|
+
if (batch.length < Math.min(limit, 100)) break;
|
|
52
|
+
}
|
|
53
|
+
return runs.slice(0, limit);
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
/** Run one `ci timings` mode and print its JSON report. */
|
|
57
|
+
export function ciTimingsCommand(argv: string[]): number {
|
|
58
|
+
const args = [...argv];
|
|
59
|
+
if (args.includes("--help") || args.includes("-h")) { writeSync(1, `${CI_TIMINGS_USAGE}\n`); return 0; }
|
|
60
|
+
const run = option(args, "--run"), job = option(args, "--job");
|
|
61
|
+
const workflow = option(args, "--workflow"), branch = option(args, "--branch"), event = option(args, "--event"), gate = option(args, "--gate");
|
|
62
|
+
const limit = option(args, "--limit"), threshold = option(args, "--threshold"), minSeconds = option(args, "--min-seconds"), top = option(args, "--top");
|
|
63
|
+
assert(!args.length, `Unexpected ci timings argument '${args[0]}'.\n\n${CI_TIMINGS_USAGE}`);
|
|
64
|
+
assert(!(run && job), "Pass --run or --job, not both.");
|
|
65
|
+
const summaryOnly = [workflow, branch, event, gate, limit, threshold];
|
|
66
|
+
// Every argument is checked before the first GitHub read.
|
|
67
|
+
if (run !== undefined) {
|
|
68
|
+
assert(summaryOnly.every(value => value === undefined) && top === undefined, "--run takes only --min-seconds.");
|
|
69
|
+
const runId = id(run, "--run");
|
|
70
|
+
const floor = integer(minSeconds, "--min-seconds", 10, 0, 86_400);
|
|
71
|
+
const repo = repository().nameWithOwner;
|
|
72
|
+
const { createdAt } = json<{ createdAt: string }>(["api", `repos/${repo}/actions/runs/${runId}`, "--jq", "{createdAt: .created_at}"]);
|
|
73
|
+
output({ repo, run: Number(runId), jobs: runSteps(createdAt, jobs(repo, runId, true), floor) });
|
|
74
|
+
return 0;
|
|
75
|
+
}
|
|
76
|
+
if (job !== undefined) {
|
|
77
|
+
assert(summaryOnly.every(value => value === undefined) && minSeconds === undefined, "--job takes only --top.");
|
|
78
|
+
const jobId = id(job, "--job");
|
|
79
|
+
const count = integer(top, "--top", 25, 1, 10_000);
|
|
80
|
+
const repo = repository().nameWithOwner;
|
|
81
|
+
// Bun and Turbo color their output; gh refuses to print escape sequences unless told they are expected.
|
|
82
|
+
const log = parseJobLog(runRead("gh", ["api", "--allow-escape-sequences", `repos/${repo}/actions/jobs/${jobId}/logs`]));
|
|
83
|
+
const misses = log.tasks.filter(task => task.cache !== "hit").map(task => task.task);
|
|
84
|
+
output({ repo, job: Number(jobId), tasks: { total: log.tasks.length, cached: log.tasks.length - misses.length, executed: misses }, files: log.files.slice(0, count), fileCount: log.files.length, casesWithoutDuration: log.casesWithoutDuration });
|
|
85
|
+
return 0;
|
|
86
|
+
}
|
|
87
|
+
assert(minSeconds === undefined && top === undefined, "--min-seconds belongs to --run and --top to --job.");
|
|
88
|
+
const thresholdMinutes = Number(threshold ?? 2);
|
|
89
|
+
assert(Number.isFinite(thresholdMinutes) && thresholdMinutes > 0, "--threshold must be a positive number of minutes.");
|
|
90
|
+
const count = integer(limit, "--limit", 50, 1, 200);
|
|
91
|
+
const repo = repository().nameWithOwner;
|
|
92
|
+
const runs = listRuns(repo, { workflow, branch, event }, count)
|
|
93
|
+
.map(item => ({ ...item, jobs: item.attempt > 1 ? [] : jobs(repo, item.id, false) }));
|
|
94
|
+
const summary = summarizeRuns(runs, { gate, thresholdMinutes });
|
|
95
|
+
assert(summary.runs > 0 || summary.excluded.missingGate === 0, `No run had a job named '${gate}'; --gate takes the gate job's name exactly as the run lists it (ci timings --run <id>).`);
|
|
96
|
+
output({ repo, workflow: workflow ?? null, branch: branch ?? null, event: event ?? null, gate: gate ?? null, ...summary });
|
|
97
|
+
return 0;
|
|
98
|
+
}
|
|
@@ -0,0 +1,181 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Pure analysis behind `agent-tool ci timings`: which jobs hold a workflow's
|
|
3
|
+
* wall clock across recent runs, where one run's jobs spend their steps, and
|
|
4
|
+
* which tasks and test files a job log executed.
|
|
5
|
+
*/
|
|
6
|
+
|
|
7
|
+
export interface TimedStep { name: string; conclusion: string | null; startedAt: string | null; completedAt: string | null }
|
|
8
|
+
export interface TimedJob { id: number; name: string; conclusion: string | null; startedAt: string | null; completedAt: string | null; steps?: TimedStep[] }
|
|
9
|
+
export interface TimedRun { id: number; event: string; attempt: number; createdAt: string; jobs: TimedJob[] }
|
|
10
|
+
|
|
11
|
+
const minutesBetween = (from: string, to: string) => (Date.parse(to) - Date.parse(from)) / 60_000;
|
|
12
|
+
const round = (value: number, places = 1) => Number(value.toFixed(places));
|
|
13
|
+
|
|
14
|
+
/** The nearest-rank value at fraction `q` of `values`; 0 when there are none. */
|
|
15
|
+
export function quantile(values: number[], q: number): number {
|
|
16
|
+
if (!values.length) return 0;
|
|
17
|
+
const sorted = [...values].sort((a, b) => a - b);
|
|
18
|
+
return sorted[Math.min(sorted.length - 1, Math.max(0, Math.ceil(q * sorted.length) - 1))]!;
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
/** A job's lane: its name without shard counters such as `2/3`, so a split suite's shards count as one. */
|
|
22
|
+
export function lane(name: string): string {
|
|
23
|
+
return name.replace(/\s*\b\d+\/\d+\b\s*/g, " ").replace(/\(\s*\)/g, "").replace(/\(\s+/g, "(").replace(/\s+\)/g, ")").replace(/\s{2,}/g, " ").trim();
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
/** Jobs that ran in this attempt: skipped jobs and jobs without both timestamps are left out. */
|
|
27
|
+
export function executedJobs(jobs: TimedJob[]): (TimedJob & { startedAt: string; completedAt: string })[] {
|
|
28
|
+
return jobs.filter((job): job is TimedJob & { startedAt: string; completedAt: string } =>
|
|
29
|
+
job.conclusion !== "skipped" && !!job.startedAt && !!job.completedAt && Date.parse(job.completedAt) >= Date.parse(job.startedAt));
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
export interface Spread { median: number; p90: number; min: number; max: number }
|
|
33
|
+
const spread = (values: number[], places = 1): Spread =>
|
|
34
|
+
({ median: round(quantile(values, 0.5), places), p90: round(quantile(values, 0.9), places), min: round(values.length ? Math.min(...values) : 0, places), max: round(values.length ? Math.max(...values) : 0, places) });
|
|
35
|
+
|
|
36
|
+
export interface JobStats {
|
|
37
|
+
name: string;
|
|
38
|
+
lane: string;
|
|
39
|
+
runs: number;
|
|
40
|
+
minutes: Spread;
|
|
41
|
+
/** Share of runs in which the job took at least the threshold: how often it did real work rather than replay a cache. */
|
|
42
|
+
overThresholdShare: number;
|
|
43
|
+
/** Seconds from the run's creation to the job's start; a steady lag is a `needs` chain, a spiky p90 is queueing. */
|
|
44
|
+
startLagSeconds: Spread;
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
export interface TimingSummary {
|
|
48
|
+
runs: number;
|
|
49
|
+
/** Runs left out: re-run attempts mix timestamps of several attempts, runs in which no job executed, and runs without the named gate job. */
|
|
50
|
+
excluded: { reruns: number; noJobs: number; missingGate: number };
|
|
51
|
+
thresholdMinutes: number;
|
|
52
|
+
/** Run creation to the gate job's end, or to the last job's end without a gate. */
|
|
53
|
+
wallMinutes: Spread;
|
|
54
|
+
/** Run creation to its first job's start: time spent waiting for any runner. */
|
|
55
|
+
firstStartLagSeconds: Spread;
|
|
56
|
+
/** How often each lane finished last among the jobs the gate waits for, which is what holds the wall clock. */
|
|
57
|
+
lastToFinish: { lane: string; runs: number }[];
|
|
58
|
+
jobs: JobStats[];
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
/**
|
|
62
|
+
* Summarize successful runs of one workflow. A gate job, when named, ends the wall clock; `lastToFinish`
|
|
63
|
+
* then counts only jobs that finished before the gate started, which are the ones it waited for.
|
|
64
|
+
*/
|
|
65
|
+
export function summarizeRuns(runs: TimedRun[], options: { gate?: string; thresholdMinutes: number }): TimingSummary {
|
|
66
|
+
const excluded = { reruns: 0, noJobs: 0, missingGate: 0 };
|
|
67
|
+
const walls: number[] = [], firstLags: number[] = [];
|
|
68
|
+
const last = new Map<string, number>();
|
|
69
|
+
const perJob = new Map<string, { durations: number[]; lags: number[] }>();
|
|
70
|
+
for (const run of runs) {
|
|
71
|
+
if (run.attempt > 1) { excluded.reruns++; continue; }
|
|
72
|
+
const jobs = executedJobs(run.jobs);
|
|
73
|
+
if (!jobs.length) { excluded.noJobs++; continue; }
|
|
74
|
+
const gate = options.gate === undefined ? undefined : jobs.find(job => job.name === options.gate);
|
|
75
|
+
if (options.gate !== undefined && !gate) { excluded.missingGate++; continue; }
|
|
76
|
+
const work = jobs.filter(job => job !== gate);
|
|
77
|
+
const end = gate?.completedAt ?? work.reduce((latest, job) => job.completedAt > latest ? job.completedAt : latest, work[0]!.completedAt);
|
|
78
|
+
walls.push(minutesBetween(run.createdAt, end));
|
|
79
|
+
firstLags.push(Math.max(0, minutesBetween(run.createdAt, jobs.reduce((first, job) => job.startedAt < first ? job.startedAt : first, jobs[0]!.startedAt)) * 60));
|
|
80
|
+
// Jobs that ended after the gate started (optional lanes, post-gate deploys) did not hold it.
|
|
81
|
+
const awaited = gate ? work.filter(job => job.completedAt <= gate.startedAt) : work;
|
|
82
|
+
const finisher = awaited.reduce<(typeof work)[number] | undefined>((latest, job) => !latest || job.completedAt > latest.completedAt ? job : latest, undefined);
|
|
83
|
+
if (finisher) last.set(lane(finisher.name), (last.get(lane(finisher.name)) ?? 0) + 1);
|
|
84
|
+
for (const job of work) {
|
|
85
|
+
const entry = perJob.get(job.name) ?? { durations: [], lags: [] };
|
|
86
|
+
entry.durations.push(minutesBetween(job.startedAt, job.completedAt));
|
|
87
|
+
entry.lags.push(Math.max(0, minutesBetween(run.createdAt, job.startedAt) * 60));
|
|
88
|
+
perJob.set(job.name, entry);
|
|
89
|
+
}
|
|
90
|
+
}
|
|
91
|
+
const jobs = [...perJob].map(([name, { durations, lags }]): JobStats => ({
|
|
92
|
+
name,
|
|
93
|
+
lane: lane(name),
|
|
94
|
+
runs: durations.length,
|
|
95
|
+
minutes: spread(durations),
|
|
96
|
+
overThresholdShare: round(durations.filter(value => value >= options.thresholdMinutes).length / durations.length, 2),
|
|
97
|
+
startLagSeconds: spread(lags, 0),
|
|
98
|
+
})).sort((a, b) => b.minutes.median - a.minutes.median || a.name.localeCompare(b.name));
|
|
99
|
+
return {
|
|
100
|
+
runs: walls.length,
|
|
101
|
+
excluded,
|
|
102
|
+
thresholdMinutes: options.thresholdMinutes,
|
|
103
|
+
wallMinutes: spread(walls),
|
|
104
|
+
firstStartLagSeconds: spread(firstLags, 0),
|
|
105
|
+
lastToFinish: [...last].map(([name, count]) => ({ lane: name, runs: count })).sort((a, b) => b.runs - a.runs || a.lane.localeCompare(b.lane)),
|
|
106
|
+
jobs,
|
|
107
|
+
};
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
export interface JobSteps { id: number; name: string; minutes: number; startOffsetMinutes: number; steps: { name: string; seconds: number }[] }
|
|
111
|
+
|
|
112
|
+
/** One run's executed jobs, longest first, each with the steps that took at least `minSeconds`. */
|
|
113
|
+
export function runSteps(createdAt: string, jobs: TimedJob[], minSeconds: number): JobSteps[] {
|
|
114
|
+
return executedJobs(jobs).map(job => ({
|
|
115
|
+
id: job.id,
|
|
116
|
+
name: job.name,
|
|
117
|
+
minutes: round(minutesBetween(job.startedAt, job.completedAt)),
|
|
118
|
+
startOffsetMinutes: round(Math.max(0, minutesBetween(createdAt, job.startedAt))),
|
|
119
|
+
steps: (job.steps ?? []).filter(step => step.startedAt && step.completedAt)
|
|
120
|
+
.map(step => ({ name: step.name, seconds: round(minutesBetween(step.startedAt!, step.completedAt!) * 60, 0) }))
|
|
121
|
+
.filter(step => step.seconds >= minSeconds),
|
|
122
|
+
})).sort((a, b) => b.minutes - a.minutes || a.name.localeCompare(b.name));
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
export interface LogTask { task: string; cache: "hit" | "miss" | "bypass" }
|
|
126
|
+
export interface LogFile { task: string | null; file: string; seconds: number; cases: number; cached: boolean }
|
|
127
|
+
export interface LogTimings { tasks: LogTask[]; files: LogFile[]; casesWithoutDuration: number }
|
|
128
|
+
|
|
129
|
+
// GitHub prefixes every log line with an ISO timestamp; Turbo and Bun color their output.
|
|
130
|
+
const TIMESTAMP = /^\d{4}-\d{2}-\d{2}T[\d:.]+Z ?/;
|
|
131
|
+
const ANSI = /\x1b\[[0-9;?]*[A-Za-z]/g;
|
|
132
|
+
const CASE = /^\((pass|fail|skip|todo)\)\s/;
|
|
133
|
+
const DURATION = /\[(\d+(?:\.\d+)?)(ms|s)\]\s*$/;
|
|
134
|
+
const CACHE = /^cache (hit|miss|bypass)\b/;
|
|
135
|
+
|
|
136
|
+
/**
|
|
137
|
+
* Read a GitHub Actions job log: each Turbo task's cache result (`##[group]<task>` followed by
|
|
138
|
+
* `cache hit`, `cache miss`, or `cache bypass`), and each Bun test file's summed case durations
|
|
139
|
+
* (`##[group]<file>:` followed by `(pass) name [12.34ms]` lines). Files a replayed (cached)
|
|
140
|
+
* task printed are marked `cached`: their durations come from the run that filled the cache.
|
|
141
|
+
*/
|
|
142
|
+
export function parseJobLog(text: string): LogTimings {
|
|
143
|
+
const lines = text.split(/\r?\n/).map(line => line.replace(TIMESTAMP, "").replace(ANSI, ""));
|
|
144
|
+
const tasks: LogTask[] = [];
|
|
145
|
+
const files = new Map<string, LogFile>();
|
|
146
|
+
const stack: { kind: "task" | "file" | "other"; name: string; cached: boolean }[] = [];
|
|
147
|
+
let casesWithoutDuration = 0;
|
|
148
|
+
for (let index = 0; index < lines.length; index++) {
|
|
149
|
+
const line = lines[index]!;
|
|
150
|
+
if (line.startsWith("##[group]")) {
|
|
151
|
+
const name = line.slice("##[group]".length).trim();
|
|
152
|
+
let ahead = index + 1;
|
|
153
|
+
while (ahead < lines.length && lines[ahead]!.trim() === "") ahead++;
|
|
154
|
+
const next = lines[ahead]?.trim() ?? "";
|
|
155
|
+
const cache = next.match(CACHE)?.[1] as LogTask["cache"] | undefined;
|
|
156
|
+
const parent = [...stack].reverse().find(entry => entry.kind === "task");
|
|
157
|
+
if (cache) { tasks.push({ task: name, cache }); stack.push({ kind: "task", name, cached: cache === "hit" }); }
|
|
158
|
+
else if (name.endsWith(":")) stack.push({ kind: "file", name: name.slice(0, -1), cached: parent?.cached ?? false });
|
|
159
|
+
else stack.push({ kind: "other", name, cached: parent?.cached ?? false });
|
|
160
|
+
continue;
|
|
161
|
+
}
|
|
162
|
+
if (line.startsWith("##[endgroup]")) { stack.pop(); continue; }
|
|
163
|
+
const trimmed = line.trim();
|
|
164
|
+
if (!CASE.test(trimmed)) continue;
|
|
165
|
+
const top = stack.at(-1);
|
|
166
|
+
if (top?.kind !== "file") continue;
|
|
167
|
+
const duration = trimmed.match(DURATION);
|
|
168
|
+
const task = [...stack].reverse().find(entry => entry.kind === "task")?.name ?? null;
|
|
169
|
+
const key = `${task ?? ""}\u0000${top.name}`;
|
|
170
|
+
const entry = files.get(key) ?? { task, file: top.name, seconds: 0, cases: 0, cached: top.cached };
|
|
171
|
+
entry.cases++;
|
|
172
|
+
if (duration) entry.seconds += Number(duration[1]) / (duration[2] === "ms" ? 1000 : 1);
|
|
173
|
+
else if (!trimmed.startsWith("(skip)") && !trimmed.startsWith("(todo)")) casesWithoutDuration++;
|
|
174
|
+
files.set(key, entry);
|
|
175
|
+
}
|
|
176
|
+
return {
|
|
177
|
+
tasks,
|
|
178
|
+
files: [...files.values()].map(file => ({ ...file, seconds: round(file.seconds) })).sort((a, b) => b.seconds - a.seconds || a.file.localeCompare(b.file)),
|
|
179
|
+
casesWithoutDuration,
|
|
180
|
+
};
|
|
181
|
+
}
|
package/src/cli.ts
CHANGED
|
@@ -11,6 +11,7 @@ import { buildScreenshots, describeScreenshots } from "./screenshots/build";
|
|
|
11
11
|
import { screenshotsStoreCommand } from "./screenshots/store/command";
|
|
12
12
|
import { spaceCommand } from "./space/command";
|
|
13
13
|
import { perfCommand } from "./perf/command";
|
|
14
|
+
import { ciTimingsCommand } from "./ci/command";
|
|
14
15
|
import { review } from "./harnesses";
|
|
15
16
|
import { carryReviewCommand } from "./review/carry";
|
|
16
17
|
import { runAgentToolAction } from "./runAgentToolAction";
|
|
@@ -59,6 +60,8 @@ Usage: agent-tool [--repo <directory>] [--config <file>] <command>
|
|
|
59
60
|
repo base-health [--branch name] [--limit N] CI health of the default branch's tip (GitHub only)
|
|
60
61
|
policy check | toolchain check
|
|
61
62
|
ci gate <needs.json|-> [--policy policy.json]
|
|
63
|
+
ci timings [--workflow file] [--limit N] [--gate job] | --run <id> | --job <id>
|
|
64
|
+
Which jobs hold a workflow's wall clock; ci timings --help lists options
|
|
62
65
|
release plan <package.json> [--github-output] [--allow-private-source]
|
|
63
66
|
release verify <package> <version> <merge-oid> --workflow name [--timeout seconds]
|
|
64
67
|
logs <file> [--max-bytes N] [--tail-lines N] Bounded local log tail
|
|
@@ -135,7 +138,12 @@ export function main(argv = process.argv.slice(2)): number | Promise<number> {
|
|
|
135
138
|
}
|
|
136
139
|
if (command === "--version") { usage(args.length === 0, "Unexpected version arguments."); writeSync(1, `${metadata.version}\n`); return 0; }
|
|
137
140
|
if (command === "run") return runCommand(args);
|
|
138
|
-
if (command === "ci") {
|
|
141
|
+
if (command === "ci") {
|
|
142
|
+
const action = args.shift();
|
|
143
|
+
if (action === "timings") return ciTimingsCommand(args);
|
|
144
|
+
usage(action === "gate", "Usage: ci gate <needs.json|-> [--policy policy.json] | ci timings [options]");
|
|
145
|
+
return gateCommand(args);
|
|
146
|
+
}
|
|
139
147
|
if (command === "release") return releaseCommand(args);
|
|
140
148
|
if (command === "proc") return procCommand(args);
|
|
141
149
|
if (command === "teardown") return teardownCommand(args);
|
|
@@ -19,7 +19,7 @@ export type Decision = "allow" | "ask";
|
|
|
19
19
|
export interface CatalogEntry { command: string; class: PermissionClass; applyClass?: PermissionClass }
|
|
20
20
|
|
|
21
21
|
export const CATALOG: CatalogEntry[] = [
|
|
22
|
-
...["--help", "--version", "logs", "runs list", "doctor", "config show", "branch check", "branch status", "commits check", "checks binaries", "repo context", "policy check", "toolchain check", "ci gate", "release plan", "release verify", "pr context", "pr checks", "pr logs", "pr preflight", "pr threads list", "versions plan", "versions check", "dependencies check-terraform-plan", "dependencies diff", "skills list", "skills check", "hooks check", "push-gate hook", "push-gate check", "repo base-health", "review carry", "images list", "graph check", "state-machines", "permissions show", "permissions check", "proc list", "perf diff", "screenshots status"]
|
|
22
|
+
...["--help", "--version", "logs", "runs list", "doctor", "config show", "branch check", "branch status", "commits check", "checks binaries", "repo context", "policy check", "toolchain check", "ci gate", "ci timings", "release plan", "release verify", "pr context", "pr checks", "pr logs", "pr preflight", "pr threads list", "versions plan", "versions check", "dependencies check-terraform-plan", "dependencies diff", "skills list", "skills check", "hooks check", "push-gate hook", "push-gate check", "repo base-health", "review carry", "images list", "graph check", "state-machines", "permissions show", "permissions check", "proc list", "perf diff", "screenshots status"]
|
|
23
23
|
.map(command => ({ command, class: "read" as const })),
|
|
24
24
|
...["bun install", "bun update", "bun remove", "bun test", "branch create", "versions bump", "versions prepare", "versions resolve-conflicts", "images build", "screenshots build", "review", "init", "proc stop"]
|
|
25
25
|
.map(command => ({ command, class: "local" as const })),
|
package/src/skills/bundled.ts
CHANGED
|
@@ -6,6 +6,7 @@ export const BUNDLED_SKILLS: Readonly<Record<string, string>> = {
|
|
|
6
6
|
"explicit-state-machines": "---\nname: explicit-state-machines\ndescription: Find implicit state machines in a repository, or across many repositories, and refactor them into explicit ones (a closed set of states, typed events, one pure transition function) without changing behavior. Use when the user asks to \"find all of the implicit state machines\", to replace tangled boolean flags or scattered status writes, or to dogfood this pass across repositories; not for adding a state-machine library or redesigning features.\n---\n\n# Explicit State Machines\n\nAn implicit state machine is code that moves through modes (idle, loading,\nfailed, done) without naming them: several booleans that are only valid in\nsome combinations, a status string written from many places, nullable fields\nwhose presence means \"we are in phase X\", or effects that chain off each other\nto advance a process. Bugs live in the combinations nobody named:\n`isLoading && error`, a retry that fires after `done`, a dialog both open and\nsubmitting twice.\n\nAn explicit machine names every state once, carries each state's data only in\nthat state, and changes state only through one function of `(state, event)`.\nThe pass finds the implicit ones, converts those where the conversion removes\nimpossible states or scattered transitions, and proves behavior did not change.\n\n## Find candidates\n\n`agent-tool state-machines` ranks tracked source files by two signals:\nlifecycle booleans toggled together (`isLoading`, `hasError`,\n`_running`, `busy.current`, `this.#rendered`), and status-like fields assigned\nthree or more string values from three or more places (`step.status = ...`).\nIt reads extensionless scripts by their shebang and is read-only. It skips\nSQL comparisons, status fields whose every write is an `UPDATE` naming its\nfrom-state, and enum case payload labels (`.ended(shouldResume: true)`).\n\n- `agent-tool state-machines [path...] [--limit N] [--min-score N] [--json]`\n scans the current repository; each path names the repository holding it.\n If the repository's pinned agent-tool lacks the command, run\n `bunx --bun @a2f0/agent-tool@latest state-machines`.\n- `--limit N` (default 25 per repository, 0 for all), `--min-score N`\n (default 3), `--json` for agents.\n\nThe script finds leads, not verdicts, and it misses whole families. Also read\nfor these by hand, starting from the places state lives (stores, providers,\nhooks, workers, sync loops, connection handlers, upload and checkout flows,\nwizards, CLI subcommands that resume):\n\n- `loading`/`error`/`data` held as separate fields, or a nullable `error`\n beside a non-null `data`; any nullable value paired with a boolean or a\n second nullable (`nowPlaying` with `interruptedNoise`, `reservation` with\n `editing`). The scanner sees booleans only.\n- State split between a context and per-component state that an effect\n re-syncs, and \"already handled\" dedupe fields that quietly mean \"confirmed\n started\".\n- Fields that are set together and cleared together (`startedAt`, `jobId`,\n `abortController`) and so encode \"running\".\n- `useEffect` chains where one effect sets state that triggers the next.\n- Retry, polling, and reconnect loops guarded by counters and flags.\n- Status columns or enums whose transitions are enforced nowhere (any writer\n may set any value), in the database or in API handlers.\n- Shell, Python, or Expect scripts that track progress with several\n variables.\n- One nullable `error` shared by a load phase and user actions: starting an\n action clears the load's failure, so the view falls back to \"Loading...\"\n after a failed load. Split a `loading | ready | failed` load machine from\n the actions' own errors.\n\n## Decide what to convert\n\nConvert a candidate only when at least one holds:\n\n1. Two or more of its variables can hold a combination that is meaningless\n (`isLoading && isError`, `data` set while `status === \"failed\"`).\n2. Its transitions are written in several places, so no single place says\n which moves are legal.\n3. A bug or missing guard follows from either (an event handled in a state\n where it must be ignored). Fix the bug in the same change, with a test that\n fails before it, and say so in the PR.\n\nLeave it alone when the flags are independent (a theme toggle and a sidebar\ntoggle are a product of two machines, not one), when there is a single\nboolean, when a status is only read (an API response's field mirrored into\nUI), when it already is a discriminated union with one writer, or when the\nmodule is about to be deleted. Also leave alone:\n\n- Status columns whose writes all live in one module, each a conditional\n update naming the states it may leave (`UPDATE ... WHERE status = $from`),\n so that module reads as the transition table. Where writers are spread out\n or name no from-state, add one `ALLOWED` table and check it in the update\n instead; a value `CHECK` alone does not enforce transitions. A database\n transition trigger only restates a guarded module and breaks fixtures that\n simulate races by setting states.\n- Monotone flags with one writer each that move one way and are read only\n by cleanup (lock held, applying, committed), and append-only accumulators.\n- Static records checked by one validator, and before/after comparisons that\n validate rather than track progress.\n- Effect and promise guards (`cancelled`, `mounted`) on their own.\n- One request in flight plus one \"run again\" flag, both written from one\n function (`pending` with `started`): three reachable phases, one writer.\n- A ref mirroring a state to block a double click before re-render\n (`isSubmitting` with `isSubmittingRef`), written together. The missing\n mirror is the bug: a `busy` guard read from a click handler's render lets\n two clicks start the work twice.\n- Flags in different components (a parent's `editing`, and `busy` in a child\n that only exists while editing): the mount already excludes the bad pair.\n- Latest-wins request counters with one writer (`++request` paired with\n `request === current`): already the recommended guard, not a machine.\n- A one-time focus-return ref written together with the close event.\n- A single set-once setup flag (`isConfigured`).\n- A memoized single teardown promise (`closing ??= teardown()`) with a\n one-way `closed` flag only that teardown sets.\n- A boolean that is only an event's payload field\n (`interruptionEnded(shouldResume:)`): it is part of an event, not state.\n\nRecord each one you leave and why, so the next pass does not reread it.\n\n## Convert\n\nFollow `references/patterns.md` for the language at hand. In every language:\n\n1. List the states and the data each one carries; list the events. Write the\n transition table before the code, and keep it in the PR body.\n2. Model states as a closed type: a TypeScript discriminated union on a\n `status` (or the repository's existing tag name), a Swift enum with\n associated values, a Kotlin sealed interface, a Python `Enum` or tagged\n dataclasses, a Go typed constant with a transition function.\n3. Write one pure `transition(state, event)` (a reducer). Make the switch\n exhaustive (`never` check, `assertNever`, `@unique` enums, sealed `when`).\n Say explicitly what an event does in a state where it does not apply:\n ignore it (return the same state) or throw in development; never fall\n through silently.\n4. Keep every guard the old code had. A `cancelled` flag or an unmount check\n that drops a stale response must become a request tag carried by the\n state and its events (only the current request may finish), never a bare\n \"is it loading?\" check, which accepts `start(A) -> reset -> start(B) ->\n succeed(A)`. Test that sequence. A cleaned-up effect's callbacks (its own\n abort's rejection included) must not dispatch either; see `patterns.md`.\n5. Move side effects out of the transition: effects run on entering a state\n (a worker loop that switches on it, or an effect keyed on the state's whole\n identity: `status` plus its request tag), not inside the reducer. An\n effect keyed on `status` alone misses `loading(A) -> loading(B)` and never\n starts B; test a replacement request.\n6. Keep call sites small: derive old booleans from the state\n (`const isLoading = state.status === \"loading\"`) where many readers use\n them, rather than rewriting every consumer in the same change.\n7. Derive old booleans so they stay stable across intermediate states: an\n effect keyed on `editing` must not refire when a replacement passes\n through `reserving`. Keep effects tied to an event, not a state (resuming\n audio on a press), in the handler.\n8. Use no new dependency. Use a state-machine library (XState, Robot) only if\n the repository already depends on it.\n9. Test the transition table directly: every legal transition, a sample of\n ignored events per state, and the impossible combinations that the old\n code allowed. Keep the existing behavior tests passing unchanged; a test\n that must change shows a behavior change, which belongs in its own PR.\n Run the new behavior tests against the old file (`git show <base>:<file>`\n into a copy kept aside) to prove the refactor changed nothing and that a\n bug's regression test fails before its fix. For output that is printed or\n saved as JSON, assert key order too.\n10. Check every new guard against existing listeners: a guard that only acts\n in `ready` breaks a listener reacting to an event fired mid-render.\n11. Treat \"initial\" props (`initialEditing`) as one-time requests, on mount or\n when they turn true, not as levels that re-apply whenever another input\n changes. Fold a mirrored prop the machine depends on (`canWrite`) into the\n state, synced by one effect declared before the request effect.\n\n## Ship\n\n- Work on a `refactor/<topic>` branch (`fix/<topic>` when the change fixes a\n bug) and ship with the repository's `ship-pr` skill: its validation, its\n independent review, its merge policy.\n- Check file-count or naming budgets (ls-lint) before adding a machine module\n and its test; a full directory may need the tests in an existing file.\n- One PR per repository per pass, unless the diff passes about 600 lines or\n spans unrelated areas; then one PR per area, each independently valid. In\n large repositories plan one PR per machine: formatted transition tables\n and their tests grow fast.\n- The PR body lists each converted machine (file, states, events, the\n impossible combinations removed, any bug fixed) and each candidate left\n alone with its reason.\n- Repository-specific findings (where machines cluster, conventions such as\n the tag name or reducer location) go in that repository's agent guidance.\n Cross-repository lessons go in `references/lessons.md` here, by PR to\n agent-tool.\n\n## Across many repositories\n\nA pass over many repositories follows the coordinating workspace's sweep\nrules (status, ledger, one delegate per repository, `ship-pr` each). Run\n`agent-tool state-machines --json` in each repository first, attach its slice\nto that repository's delegate brief, and remind delegates to read beyond the\nscript's list.\nRepositories whose push hook or ship policy runs a full browser, simulator,\nor package gate need a heavy slot to ship: a delegate without one prepares a\nreviewed commit or open PR and hands off to a finisher that holds one.\n\n## Ownership\n\nagent-tool (`a2f0/agent-tool`) owns this skill in\n`skills/explicit-state-machines/`, and the `state-machines` scanner with its\ntests in `src/stateMachines/`. Repositories get it from\n`agent-tool skills install --apply`; do not edit the installed copy. Change it\nin agent-tool by PR, and send cross-repository lessons to\n`references/lessons.md` there. Repository-specific conventions still go in\nthat repository's `AGENTS.md`.\n",
|
|
7
7
|
"open-issue": "---\nname: open-issue\ndescription: Open a GitHub issue the user explicitly requested, assigned to the authenticated GitHub user, with a reviewable title and body.\n---\n\n# Open Issue\n\nOpen an issue only when the user explicitly asks for one; finding a bug,\nrecording evidence, or following another skill does not authorize it. Follow\nrepository guidance for where issues belong, labels, and templates.\n\nResolve the target repository with `agent-tool repo context` (its `repo`\nfield) from the checkout, or the `owner/repo` the user named; never infer it\nfrom a folder name. Before creating, search open issues for a duplicate:\n\n```sh\ngh issue list --repo <owner/repo> --state open --search '<key words>' --json number,title,url\n```\n\nIf one matches, report it instead of opening another, and assign it with\n`gh issue edit <number> --repo <owner/repo> --add-assignee @me` when the user\nwants it tracked.\n\nWrite a specific title and a body that states the observed behavior, the\nexpected behavior, and reproduction steps or evidence (commands, versions,\nlinks). Never include secret values. Use only labels that already exist\n(`gh label list --repo <owner/repo>`). Put the body in a temporary file, then\ncreate the issue assigned to the authenticated GitHub user:\n\n```sh\ngh issue create --repo <owner/repo> --title '<title>' --body-file /path/to/issue-body.md --assignee @me\n```\n\nAlways pass `--assignee @me`; assign other people only when the user names\nthem, in addition to `@me` unless the user says otherwise. Confirm the result\nwith `gh issue view <url> --json url,assignees` and, if the assignee is missing,\nadd it with `gh issue edit <url> --add-assignee @me`. Report the issue URL and\nits assignees, or the exact error if assignment failed.\n",
|
|
8
8
|
"open-pr": "---\nname: open-pr\ndescription: Open a GitHub pull request for the current feature branch with a validated title and a reviewable description.\n---\n\n# Open PR\n\nUse the installed `agent-tool`. Follow repository policy for validation, commits,\nand branch naming. Resolve the repository and default branch with `agent-tool repo context`;\ndo not assume the branch is named main. Preserve unrelated work and finish\nrequested changes and appropriate checks before publishing them.\n\nEnsure the intended commit is on a feature branch and use\n`agent-tool branch push <reviewed-head> --remote <remote>` through normal hooks.\nIt names the destination explicitly and verifies local/remote HEAD afterward;\na changed result needs another review. Respect existing push authorization.\nIf the user only requested a draft description, prepare it without publishing.\n\nWrite a title that satisfies the data-only `agent-tool.json` subject policy.\nDescribe the concrete resulting behavior and relevant validation. When the\nbranch changes package manifests, run\n`agent-tool dependencies diff --base <base-oid>` and name every `newPackages`\nentry in the body with its manifest and version, so a reviewer sees new\nthird-party code however it was added. Put multiline body text in a temporary\nfile, then run:\n\n```sh\nagent-tool pr open 'feat: describe the change' --body-file /path/to/pr-body.txt\n```\n\nOmitting the title uses the latest commit subject. The tool refuses duplicate\nopen PRs and requires the branch to be pushed at its local HEAD. It does not\npush for you. Resolve a fork's head/base identities explicitly if the repository\nuses fork PRs; the initial open helper supports same-repository branches.\n\nReport the created PR link and any remaining validation or review work. Run\n`agent-tool teardown` first, stop what the work started, and report what remains.\n",
|
|
9
|
+
"optimize-ci": "---\nname: optimize-ci\ndescription: Cut a repository's CI wall-clock time in measured rounds - find the job that holds the critical path across recent runs, then split, parallelize, cache, or gate it without checking less, shipping each change through ship-pr. Use when the user asks to speed up CI, a pipeline, or required checks; not for making individual tests faster, production performance, or page loads (performance-pass).\n---\n\n# Optimize CI\n\nA CI pass makes developers wait less for the same verdict. Every test, check,\nand required job that ran before still runs; what changes is where and when it\nruns and what is reused. A faster pipeline that checks less is a regression,\nnot a win.\n\n## Measuring\n\n`agent-tool ci timings` reads GitHub Actions through `gh` and changes nothing.\nWhen a repository's agent-tool pin predates the command, run\n`bunx --bun @a2f0/agent-tool@latest ci timings`.\n\n| Command | Shows |\n| --- | --- |\n| `ci timings --workflow <file> --gate <job> [--event pull_request] [--limit 80]` | Over the latest successful first-attempt runs: wall clock (median, p90), the lane that finished last in each run, and every job's duration, how often it took at least `--threshold` minutes (did real work rather than replay a cache), and how long it waited to start |\n| `ci timings --run <id>` | One run's jobs, longest first, with their steps |\n| `ci timings --job <id>` | One job's log: which Turbo tasks executed and which replayed from cache, and Bun test files ranked by summed case time |\n\nA lane is a job name without shard counters, so `Test (api 1/3)` and\n`Test (api 2/3)` both count as `Test (api)`.\n\n## Procedure\n\n1. Scope. Read the repository's guidance and CI policy: required checks, any\n aggregate gate job, path filters, cache bridges, and merge rules. The target\n is the wall clock developers wait on: the median and p90 of pull-request\n runs, measured to the gate job.\n2. Baseline. Run `ci timings` over 50 to 80 runs, pull requests and the default\n branch separately. Record wall median and p90, `lastToFinish`, the top jobs'\n medians, and `overThresholdShare`. A scheduled uncached run, where the\n repository has one, shows each job's cost without cache replay.\n3. Find the critical path. The lane that finishes last in most runs is the\n target; break it down with `--run` (which step) and `--job` (which task or\n test file). Then name the next two or three lanes: removing the first exposes\n them, so plan a round that brings all of them under the target.\n4. Choose levers, safest first:\n - Split serial work across runners. A long suite hidden in a catch-all job\n sets that job's length; give it its own matrix entries. Balance shards by\n measured time, not file count (Bun's `--shard` with `--timings`,\n Playwright's `--shard` from spec durations): a count split of uneven files\n is lopsided. No shard is shorter than its longest file, so split that file\n when its cases are independent.\n - Use the cores the runner has. Check effective parallelism: test runners'\n CI defaults (Playwright uses half the cores), tool flags (TLC\n `-workers 1`), and pool sizes. Raise them only with measured memory\n headroom, and keep timing-sensitive end-to-end suites on their own runners\n rather than crowding one.\n - Schedule longest first in any pool, so a long item never starts last.\n - Cache what every run rebuilds: toolchains, browsers, package stores,\n compiler output (Xcode DerivedData and SwiftPM, Gradle), and task results.\n Key each cache on exactly what its output depends on.\n - Keep cache keys and path filters narrow. A file every pull request touches\n (a lockfile that version bumps rewrite, version fields, embedded build\n versions) silently defeats both. A job with a high `overThresholdShare`\n that should usually be cached points to one.\n - Remove duplicate work, such as one task in two jobs racing to fill the\n same cache entry.\n - Never delete or skip tests, loosen assertions or timeouts, drop a backend,\n make a required check optional, or let a cache hit stand in for a check\n whose inputs it does not cover.\n5. Prove each change. Ship one lever per PR with `ship-pr`. A task cache can\n hide the change, so measure on a run that executes the lane: changed task\n arguments or inputs miss on their own; otherwise dispatch an uncached run.\n Give baseline and after numbers with run ids in the PR body. Keep a policy\n test beside the workflow that fails when a shard or gated job goes missing.\n6. Re-measure after merging, with the same command over runs created after the\n merge, and report the change in median and p90 wall clock. Start the next\n round from step 3 with the new top lane.\n7. Learn. Repository-specific findings go in that repository's guidance.\n Cross-repository lessons go in agent-tool's\n `skills/optimize-ci/references/lessons.md` by PR, naming the repository and\n PR; [the installed copy](references/lessons.md) is read-only.\n\n## Pitfalls\n\n- GitHub Actions caches are scoped. A pull request reads entries from its own\n ref and the default branch, never another pull request's, and one that starts\n before the default branch's run finishes misses the entries that run is still\n writing. Check timing before calling a miss a key bug.\n- Turbo and Nx hash task arguments, so shards cache independently only when the\n shard argument reaches the task.\n- A cached job still costs a runner, its setup, and a concurrency slot.\n Account limits, macOS especially, queue jobs as shards multiply: compare\n `startLagSeconds` p90 before and after, and let path filters skip lanes a\n change cannot affect.\n- A re-run attempt mixes timestamps from several attempts; `ci timings` leaves\n re-runs out, and manual analysis should too.\n- Turbo buffers a task's output until it ends, so log timestamps show\n completion, not progress. Use the test runner's own case durations.\n- Turning a job into a matrix renames its check (`Web E2E` becomes\n `Web E2E (1/3)`). Update branch protection, rulesets, and the merge helper's\n required checks together, or require an aggregate gate job instead.\n- Changing a shard count reshuffles which files share a worker; with test\n isolation off, that can surface leaks between files. Run every new shard\n composition before pushing.\n- Config chosen on `CI` (reporters, plugins, entries) looks different to\n static analysis locally and on CI, so a check passes locally and fails on CI.\n Keep config the same everywhere, or run those checks with `CI=true` too.\n- A recorded-durations file only orders and balances work. It must ignore\n entries for items that no longer exist and weight unknown ones, or a rename\n in any pull request fails CI on a scheduling hint.\n- Merge policy is part of the wall clock: a check that forces queued pull\n requests to integrate after every merge reruns their CI one at a time.\n\n## Ownership\n\nagent-tool (`a2f0/agent-tool`) owns this skill at `skills/optimize-ci/` and the\n`ci timings` command at `src/ci/`, with its tests beside it; `agent-tool skills\ninstall --apply` installs it in each adopting repository. Change it there,\nnever in an installed copy. A repository's CI layout, required checks, and\nmeasured baselines belong in its own docs.\n",
|
|
9
10
|
"performance-pass": "---\nname: performance-pass\ndescription: Make a page or embedded viewer load faster without changing what it shows, in measured rounds that each ship through ship-pr, then carry the release to every consumer. Use when the user asks to speed up loading, startup, or first render, or to dogfood a performance round; not for changing visual quality, content, or features.\n---\n\n# Performance Pass\n\nA pass is a few rounds. Each round measures, changes one thing, proves the\noutput is unchanged, measures again, and ships. Numbers decide what lands;\nimpressions do not. What the page shows is fixed: a faster load that changes a\npixel, a mesh, or a behaviour is a regression, not a win.\n\n## The measuring command\n\n`agent-tool perf` runs the measurements; run the repository's pinned\nagent-tool (`bun run agent-tool perf` or `node_modules/.bin/agent-tool perf`).\nIt drives Chrome through the measured repository's own `playwright`, found\nfrom the working directory or `--from <directory>` inside the checkout it\nruns in, and never fetches one.\nFrom a matrix workspace, measure a checkout with\n`agent-tool perf <command> --from checkouts/<name>`. If the pinned agent-tool\npredates the command, run `bunx --bun @a2f0/agent-tool@latest perf`.\n\n| Command | Does |\n| --- | --- |\n| `serve <dir> [--port N] [--http1]` | Serves a production build over HTTP/2 with gzip (compressed before the first request) and ETag revalidation, as a CDN does, never following links out of the directory. Start it with `agent-tool proc start --label serve -- node_modules/.bin/agent-tool perf serve <dir>` and stop it with `agent-tool proc stop`. |\n| `measure <url> --ready <js>` | Cold, cache-disabled loads timed from the start of navigation (it waits only for the commit, never the `load` event); prints the median time until the `--ready` expression is true, requests, bytes, when the finished requests ended, and how many were still pending. `--waterfall` lists requests; `--profile` adds CPU self and inclusive times from an extra, unsampled run; `--json` prints the report as JSON. |\n| `shot <url> --ready <js> --out <png>` | Screenshot of the ready state with a seeded `Math.random`, for fidelity diffs. `--eval <js>` runs an interaction first (switch a mode on); `--hide <css>` hides random decoration, reaching into open shadow roots. |\n| `diff <a.png> <b.png>` | Counts differing pixels, and the busiest 50-pixel cells, without a browser; exits 1 on any. |\n| `graph <dir> <entry...> [--out <file>]` | Relative static and dynamic import closure of ES modules, as JSON. |\n\nDefaults: 5 runs, 40 ms latency, 20 Mbps, no CPU slowdown, 1600x900. Always\nalso measure a slow profile, `--latency 150 --mbps 5 --cpu 4`, since a\nphone's CPU, not the network, is often what remains.\n\n## Procedure\n\n1. Scope. Name the pages, the ready signal (what \"usable\" means: first frame\n drawn, `aria-busy` cleared, a hydration flag), and every consumer that\n embeds the package. Read each repository's guidance first; it decides\n validation, versioning, and shipping.\n2. Baseline. Build the production output from the base commit into a scratch\n copy (`git archive <base> | tar -x -C <dir>`, link `node_modules`), serve\n it, and measure both profiles with `--waterfall --profile`. Check the live\n deployment's headers with `curl -sSI -H 'Accept-Encoding: br, gzip'`\n (compression, `cache-control`, HTTP version): local serving only stands in\n for them.\n3. Read the time. Split ready time into network (request chain depth, bytes,\n queueing) and main thread (the CPU profile's inclusive table). A waterfall\n whose requests start in steps is a dependency chain; a long tail after\n `network done` is CPU.\n4. Choose one change, safest first:\n - Transport: preload hints for a known module graph, fewer chained\n requests, compression, cache headers. Output cannot change.\n - Deferral: build what the first frame does not show (hidden modes, unused\n layers) on first use instead of at startup. The first frame must be\n identical, and the deferred feature must still work when first used.\n - Same-output speedups: faster algorithms, fewer allocations, typed arrays,\n reused buffers. Prove byte-identical output (geometry arrays, generated\n files), not just \"looks the same\".\n - Never, unless the user asks: lower resolution, level of detail,\n sampling, lossy re-encoding, removing content, or changing a bundler or\n vendored engine against repository guidance.\n5. Prove fidelity. Run the repository's own pixel, geometry, and browser\n suites, and `shot` + `diff` the ready state of base and change at the same\n viewport. First diff two base shots against each other: if the page is\n not deterministic even when seeded, say which regions vary and compare\n with that in mind, never by loosening the repository's own thresholds.\n6. Measure again with the same commands and runs. Keep the change only when\n both medians improve beyond the base's own min-max spread; report both\n profiles' before and after medians and network-done times.\n7. Ship with `ship-pr` in that repository, the measurements in the PR body.\n Then, for each consumer, bump to the published version with its own\n `ship-pr`, and measure the consumer's page the same way when it can be\n served locally.\n8. Learn. Repository-specific findings (what dominated, what was tried and\n rejected and why) go in that repository's agent guidance or skill.\n Cross-repository lessons go in agent-tool's\n `skills/performance-pass/references/lessons.md`, by PR there. Next round\n starts from step 3 with the new profile.\n\n## Pitfalls\n\n- Serve over HTTP/2. Browsers open six HTTP/1.1 connections per host, so a\n plain local server queues a module graph that a CDN serves at once, and\n makes preload changes look worthless.\n- Compress once per file, not per request: a server compressing on every\n request adds its own CPU time to the waterfall.\n- Preload links that hosts' pages receive must go in the document head (not\n a shadow root) and should be removed once loading settles; skip assets a\n host replaces, such as a shared engine.\n- Medians of one or two runs are noise; run at least five, seven for a\n close call. Check `uptime` first: other sessions' test suites inflate the\n CPU-throttled profile most. Under load, interleave base and change runs,\n and back a CPU change with `--profile`, comparing the changed function's\n inclusive time against what remains, rather than wall medians alone.\n- Deferring work is only output-neutral if nothing the deferred work reads\n changes before it runs. Find every writer of its inputs and make it run\n before the first one, then test a deferred instance against an eager one\n step by step.\n\n## Ownership\n\nagent-tool (`a2f0/agent-tool`) owns this skill at `skills/performance-pass/`\nand the command at `src/perf/`, with its tests beside it; `agent-tool skills\ninstall --apply` installs it in each adopting repository. Change it there,\nnever in an installed copy.\n",
|
|
10
11
|
"reset": "---\nname: reset\ndescription: Return a clean checkout to its updated default branch after confirmed shipping or an explicit checkout cleanup request.\n---\n\n# Reset\n\nThis is checkout cleanup, not a destructive Git reset. Read repository guidance\nfor setup and hooks. Determine the default branch through the repository's\nremote metadata rather than assuming main.\n\nFor post-merge cleanup, preview with\n`agent-tool repo cleanup <PR-number> <shipped-head>`, then run it with `--apply`\nwithin the authorized cleanup scope. It requires a confirmed MERGED PR, refuses\nthe default and `branch.exempt` branches, preserves local edits, checks exact\nlocal/remote feature commits, verifies the merge is on the default branch, and\nfast-forwards that branch. By default it prunes the\nshipped local feature branch and deletes the matching remote branch if present.\nLocal pruning also applies after a squash merge or when GitHub already deleted\nthe remote branch; a missing remote is not evidence that local cleanup is done.\nPass `--keep-branch` when the user asked to preserve both feature refs.\nRead the receipt's completed steps if a later operation fails; do not claim full\ncleanup from a partial result. Verify the final branch and clean worktree, and\ncheck that `git branch --list <feature-branch>` is empty unless keeping the branch.\nIf the feature branch is checked out in another worktree, shared cleanup reports\na partial failure after updating the default branch and leaves both feature refs\nin place; preserve that worktree and report the remaining cleanup.\n\nRemote branch deletion uses GitHub REST after checking the live ref to avoid\npre-push hooks. The API has no atomic expected-OID delete guard; the check and\ndeletion retain a small concurrent-update window. Fork PRs require manual remote\nhandling and are refused by the shared cleanup command.\nUse a repository's stronger cleanup procedure when required, including atomic\nremote deletion or additional local verification; do not weaken it to use the\nshared command. The same local pruning and keep-branch outcomes still apply.\n\nFor an explicit checkout cleanup without a merged PR, preserve all feature refs:\ncheck worktree/index, resolve the default branch with `repo context`, fetch it,\nswitch, and update by fast-forward only. Never discard or automatically stash\nedits, force a diverged default branch, or infer shipping from Git ancestry after\na squash merge.\n\nRun `agent-tool teardown` and stop what the finished work left running\n(`teardown --apply` for recorded processes); report anything that remains.\nRun the repository's documented dependency/hook setup if required. When copied\nhooks are configured, use `agent-tool hooks check` and `hooks install --apply`;\ninspect unmanaged hooks before an explicit `--adopt`, which backs them up.\nDo not assume a package manager. Report final branch, commit, whether the shipped\nlocal branch was pruned or preserved, and unfinished cleanup or setup.\n",
|
|
11
12
|
"seo-optimization": "---\nname: seo-optimization\ndescription: Audit and improve how a repository's websites appear in search results and link previews, covering titles, descriptions, canonical URLs, Open Graph, structured data, robots.txt, sitemaps, status codes, and keeping non-production tiers out of search indexes. Use for an SEO audit or optimization pass, not copywriting or general feature work.\n---\n\n# SEO Optimization\n\nMake every production page say what it is in the HTML that is served\nbefore JavaScript runs, name one canonical URL, and be discoverable through\nrobots.txt and a sitemap. Keep every non-production tier out of search\nindexes. Judge the deployed result, not the source: a correct template that\nnever reaches the live response is not a fix.\n\n## Establish scope\n\nRead the repository's instructions and the docs they point to, including\nsetup, validation, versioning, deployment, and title policy. Use the user's\nscope. A report-only request stays read-only. An optimization pass may make\nreversible changes in the repository and ship them through its normal\nworkflow when shipping is authorized; existing explicit authorization still\napplies, so do not ask for it again. On a repeat pass, read the previous SEO\nchange and its docs, keep the decisions it recorded, and re-check what it\ncalled compliant against the current standard; when it left no change,\naudit from scratch.\n\nThis skill does not by itself authorize DNS changes, zone or CDN settings,\nsearch console registration, store listings, or production content rewrites.\nWrite titles and descriptions from copy the site or repository already has.\nNever invent product claims, platforms, prices, ratings, or reviews, and never\nadd links to store pages that are not live.\n\n## Inventory hosts\n\nList every public hostname the repository serves, by tier, from hosting\nconfiguration (for example `wrangler.jsonc` routes), infrastructure code,\ndeploy workflows, and docs. Classify each one:\n\n- **content**: marketing site, landing page, resume, or documentation that\n should rank. A standalone web tool with no separate marketing site is a\n content host for its landing page.\n- **app**: an interactive application or app shell, often `app.*` or\n `demo.*`, whose marketing lives elsewhere.\n- **internal**: admin dashboard, asset gallery, or API host. A package's\n viewer or demo site, whose pages other sites copy, is internal unless the\n repository or the user says it should rank; ask when it is unclear.\n- **non-production**: staging, preview, or any other tier that is not the\n production site.\n\nFor each host, find how it is built and deployed. Note whether each tier has\nits own build or one artifact is promoted, whether a merge deploys or a\nperson runs a command, and whether a Worker or server script answers some\nresponses itself. These facts decide where a tier-specific header can live.\nInclude hosts the platform adds on its own, such as `*.workers.dev` and\nper-version preview URLs, which serve duplicate copies of the site.\n\nProbe each host's current state with `agent-tool seo probe`, run through the\nrepository's pinned agent-tool: `bun run agent-tool seo probe <host> [path]`,\nor `node_modules/.bin/agent-tool seo probe <host> [path]` where there is no\npackage script. It reports a page's title, description, canonical, robots\nmeta, `X-Robots-Tag`, Open Graph and Twitter tags, preview image, JSON-LD\ntypes, and h1 count, then the site's robots.txt, sitemap, missing path, and\n`http://` behavior. `--page` skips the site files;\n`--headers <host> <path>...` prints one line per path without following\nredirects, for checking headers on assets, redirects, and errors; `--links`\nlists the page's internal links that do not answer 200 directly; and\n`--sitemap` checks every sitemap URL's status, canonical, and robots, and\nreports duplicate titles and descriptions. The mode flag comes first, the\nhost is a hostname with an optional port, and each path starts with `/`. The\nprobe matches text patterns rather than parsing HTML, so confirm anything\nsurprising in the raw response before acting on it. A `000` status means no\nresponse, including a URL it refused to request: one that is not HTTP or\nHTTPS, or one on a private or local address that a page or redirect, not the\ncommand line, named. Set `SEO_PROBE_USER_AGENT` to a browser user agent to see\nwhat a zone injects only for browsers.\n\nCheck whether the default branch already has merged work that has not been\ndeployed, because a deploy ships it too. Deployment listings often do not\nname a commit. The strongest check is to build the default branch with\nproduction settings and compare its files with the live ones byte for byte;\notherwise compare deploy times with merge times (for CI deploys, the head\ncommit of the deploy runs), read a version marker in the live HTML or bundle,\nor run the repository's deploy verifier read-only. A deploy may also apply\ndatabase migrations; list pending ones read-only first.\n\n## Apply the standard\n\nApply [references/standard.md](references/standard.md), which holds the\nchecklist for each host class; read \"Every host\" and the sections for the\nclasses you found. Its outcomes, in one line each:\n\n- **Non-production**: noindex on every response and page, crawlable, no\n canonical or sitemap. Production is never noindexed, except its error page\n and paths deliberately kept out of search.\n- **Content**: complete static head, preview image, structured data,\n robots.txt, sitemap, and real 404s.\n- **App**: descriptive shell metadata and a real robots.txt; a canonical only\n when routes are not distinct public content.\n- **Internal**: noindex for HTML surfaces; API hosts only when trivial.\n\nPlatform specifics live in\n[references/cloudflare-workers.md](references/cloudflare-workers.md) (static\nasset headers, trailing slashes, not-found handling, Cloudflare's managed\nrobots.txt) and [references/frameworks.md](references/frameworks.md) (Astro,\nNext.js static export, Vite single-page apps, Bun's HTML bundler,\nreact-native-web, service workers, and `agent-tool images` for preview\nimages). Read the sections that match the repository.\n\nKeep changes proportionate: metadata, robots, sitemaps, status codes, and\nlight heading or `alt` fixes on pages you touch. Record larger work, such as\nprerendering JavaScript-only content, performance refactors, localized URL\ntrees, or redirects that need DNS, as recommendations.\n\n## Validate and verify\n\nRun the repository's full documented validation. Build every tier you\nchanged and inspect its output: each HTML `<head>`, `_headers` or equivalent,\nrobots.txt, the sitemap, and the preview image. Add tests where the\nrepository has a natural place for them:\n\n- metadata is present in the static HTML with JavaScript disabled;\n- the non-production build carries noindex and the production build does not;\n- every sitemap URL equals the canonical URL of the page it lists;\n- every internal link answers without a redirect;\n- an unknown path returns 404 when served by the real hosting runtime, not a\n development server that answers every path with the app, and the error\n page's own URL (such as `/404`) carries noindex.\n\nBefore changing a title or description, search the tests for the old text.\nShell snippets added to docs must not use `path` as a variable name, because\nzsh ties it to `PATH`.\n\nAfter deploying, probe every host on every tier; the probe adds a\ncache-busting query. Confirm that production carries no noindex in headers or\nmarkup, that the preview image at the URL the page names answers 200 with an\nimage type and the declared size, and that every sitemap URL answers 200\nwithout a redirect. Confirm that each non-production host sends the header\non HTML, assets, fallbacks, and redirects. Record what the CDN did to\nrobots.txt.\n\n## Report\n\nUse the repository's report convention, or put the evidence in the PR and\nthe final summary:\n\n- hosts with their classification and live result, per tier;\n- the changes made, and what was deliberately left unchanged, with reasons;\n- recommendations ordered by impact, with an owner or the decision they need;\n- questions that only the user can answer, such as whether user-generated\n public pages should be indexable, or which URL form legal pages should use.\n\nOut-of-scope items belong in recommendations unless the user authorizes\nthem: search console and Bing Webmaster verification and sitemap submission,\ninfrastructure changes such as `www` redirects and zone settings (see\n[references/cloudflare-workers.md](references/cloudflare-workers.md)), CDN\nrobots and AI-crawler settings, store links and smart app banners before\nstore IDs exist, app association files, and content or performance work.\nKeep reusable procedure in this skill and dated findings in the report.\n\n## Ownership\n\nagent-tool (`a2f0/agent-tool`) owns this skill in `skills/seo-optimization/`,\nand the `seo probe` command with its tests in `src/seo/`. Repositories get\nthe skill from `agent-tool skills install --apply`; do not edit the installed\ncopy. Change it in agent-tool by PR. A repository's hosts, tiers, and deploy\nchecks belong in its own docs.\n",
|
|
@@ -32,6 +33,10 @@ export const BUNDLED_SKILL_REFERENCES: Readonly<Record<string, Readonly<Record<s
|
|
|
32
33
|
"references/lessons.md": "# Lessons\n\nCross-repository lessons from explicit-state-machine passes. Add one when a\npass learns something the next repository needs; keep repository-specific\nfindings in that repository's guidance.\n\n- The script's `flags` signal skips `cancelled` and `settled`: effect cleanups\n and promise races set them once as guards, which is not a machine.\n- Type members and returned object literals (`status: \"idle\"`) are how an\n explicit machine names its states, so the `status` signal counts only\n assignments and setter calls.\n- The first sweep (16 repositories) found real machines the scanner missed:\n React refs (`busy.current`), `#private` fields, in-place writes to nested\n objects (`record.steps[i].status`), lifecycle booleans not named `is*`\n (`booting`, `paging`), extensionless and Expect scripts, and nullable values\n paired with flags. The first five are now signals; read for the last by hand.\n- A ref mirroring a state (`isSubmitting` with `isSubmittingRef`) now shows as\n two flags; it is worth reading, since the pair can disagree.\n- Server status columns in balebase and devopsrockstars were already guarded:\n every write, in one module, is a conditional update naming the states it\n may leave. The scanner still lists them; the skill says when that suffices.\n- Repositories with no runtime state (seed data, one-shot CLIs, dotfiles)\n closed as `unchanged` within minutes; let them, and record what was read.\n- Converting found real bugs: a step that stayed `running` forever after its\n runner failed to start, a gallery acting on a detached render, a bootstrap\n gate blocked forever when prerequisites vanished mid-run, two menus closing\n on one press, duplicate stop logs on a second focus loss.\n- Second and third rounds in balebase and tearleads, driven by the widened\n scanner, found one more real bug (a checkout link minting two Stripe\n sessions on a double click) and several false positives now named in the\n skill's leave-alone list: in-flight-plus-rerun flags, ref mirrors, and flag\n pairs split across a parent and a conditionally mounted child.\n- Bug fixes the sweep surfaced outside state machines shipped as their own\n `fix/` PRs: a swallowed settings-write error, a partial download cached\n forever, an audio session never released, a verify step failing during\n registry propagation, and a CI runner image that broke browser tests.\n- A nullable `error` shared by a load and user actions hid a real bug in\n devopsrockstars' Stripe payment step: after a failed load, Cancel cleared\n the error and the step showed \"Loading...\" again. A `loading | ready |\n failed` load machine with separate action errors fixed it\n (devopsrockstars#898). The scanner sees booleans only; read for it by hand.\n- The second sweep's perennial false positives are now named: guarded SQL\n status updates (devopsrockstars checkout and webhooks, balebase contracts\n and jobs) and enum payload labels are skipped by the scanner, along with\n `*.testUtils.*` files; latest-wins request counters, set-once setup flags,\n one-time focus-return refs, and memoized teardown promises are in the\n skill's leave-alone list.\n An update whose `WHERE` has an `OR`, a `NOT` or a subquery still counts,\n even when every branch names the from-state (balebase finance): read it by\n hand.\n",
|
|
33
34
|
"references/patterns.md": "# Patterns\n\nBefore and after shapes per language. Match the repository's existing names\n(tag field, reducer file layout, error helpers) over these.\n\n## TypeScript and React\n\nBefore: three booleans and two nullable fields, eight combinations, four valid.\n\n```ts\nconst [isLoading, setIsLoading] = useState(false);\nconst [error, setError] = useState<Error | null>(null);\nconst [data, setData] = useState<Item[] | null>(null);\n```\n\nAfter: one union, one reducer, booleans derived for readers.\n\n```ts\nexport type LoadState =\n | { status: \"idle\" }\n | { status: \"loading\"; request: number }\n | { status: \"failed\"; error: Error }\n | { status: \"loaded\"; items: Item[] };\n\nexport type LoadEvent =\n | { type: \"start\"; request: number }\n | { type: \"succeed\"; request: number; items: Item[] }\n | { type: \"fail\"; request: number; error: Error }\n | { type: \"reset\" };\n\n/** Only the request that is still current may finish the load. */\nconst current = (state: LoadState, request: number) =>\n state.status === \"loading\" && state.request === request;\n\nexport function transition(state: LoadState, event: LoadEvent): LoadState {\n switch (event.type) {\n case \"start\":\n return { status: \"loading\", request: event.request };\n case \"succeed\":\n return current(state, event.request) ? { status: \"loaded\", items: event.items } : state;\n case \"fail\":\n return current(state, event.request) ? { status: \"failed\", error: event.error } : state;\n case \"reset\":\n return { status: \"idle\" };\n default:\n return assertNever(event);\n }\n}\n\nfunction assertNever(value: never): never {\n throw new Error(`Unhandled event: ${JSON.stringify(value)}`);\n}\n\n// In the component:\nconst [state, dispatch] = useReducer(transition, { status: \"idle\" });\nconst isLoading = state.status === \"loading\";\n// Keyed on the request, not just the status, so a replacement request starts.\nconst request = state.status === \"loading\" ? state.request : undefined;\nuseEffect(() => {\n if (request === undefined) return;\n const abort = new AbortController();\n // The cleanup's own abort rejects the fetch; that rejection must not\n // dispatch, or a re-run of this effect for the same request (Strict Mode,\n // a dependency change) records a failure the user never had.\n let active = true;\n fetchItems(abort.signal).then(\n items => { if (active) dispatch({ type: \"succeed\", request, items }); },\n error => { if (active) dispatch({ type: \"fail\", request, error }); },\n );\n return () => { active = false; abort.abort(); };\n}, [request]);\n```\n\nThe request tag rejects results from a superseded request; the `active` flag\nrejects callbacks from a cleaned-up effect for the same request. Keep both, and\ntest the replay: mount, unmount, mount again (Strict Mode), then resolve, and\nexpect `loaded`, not `failed`.\n\n- Never drop a cancellation guard without replacing it. A bare\n `status === \"loading\"` check accepts a stale result in\n `start(A) -> reset -> start(B) -> succeed(A)`; tag each request (a counter\n or the `AbortController` itself) and let only the current one finish, as\n above, with that sequence as a test. Keep aborting the network work too.\n- Stores (Zustand, Redux, signals): keep the union as the store's state and\n the reducer as its only writer; actions dispatch events.\n- Classes and long-lived loops (sync workers, socket connections): a private\n `state` field of the union type, a `send(event)` method that applies\n `transition`, and the loop `switch`es on `state.status`.\n- Server status columns: a `ALLOWED: Record<Status, readonly Status[]>` table\n and one `moveTo(row, next)` that checks it inside the update's transaction\n (`UPDATE ... WHERE status = $from`), so concurrent writers cannot skip a\n state.\n\nTest with a table:\n\n```ts\ntest.each([\n [{ status: \"idle\" }, { type: \"succeed\", request: 1, items: [] }, { status: \"idle\" }],\n [{ status: \"loading\", request: 1 }, { type: \"succeed\", request: 1, items: [] }, { status: \"loaded\", items: [] }],\n [{ status: \"loading\", request: 2 }, { type: \"succeed\", request: 1, items: [] }, { status: \"loading\", request: 2 }],\n [{ status: \"loaded\", items: [] }, { type: \"fail\", request: 1, error }, { status: \"loaded\", items: [] }],\n] as const)(\"%o + %o\", (state, event, next) => {\n expect(transition(state, event)).toEqual(next);\n});\n\ntest(\"a stale request cannot finish a newer one\", () => {\n const events: LoadEvent[] = [\n { type: \"start\", request: 1 }, { type: \"reset\" }, { type: \"start\", request: 2 },\n { type: \"succeed\", request: 1, items: stale },\n ];\n expect(events.reduce(transition, { status: \"idle\" })).toEqual({ status: \"loading\", request: 2 });\n});\n```\n\n### More React and class shapes\n\n- **A handler, not an effect, starts the work** (a sign-in button): take the\n request number from a `useRef` counter, dispatch `start` with it, and have\n the async handler dispatch `succeed`/`fail` with the same number.\n- **Synchronous re-entrance** (two clicks before a render): keep the current\n state in a ref that one `send(event)` updates and that returns the next\n state; the caller starts work only if its own request entered `loading`.\n- **A queue that spans effect runs** (read one page at a time, queue one\n refresh): keep the machine in a ref with a `useState` copy for rendering,\n written by one `send`. A superseded request that must still finish (to start\n the queued refresh) carries `current: false` instead of being dropped.\n- **A handler that both changes state and decides an output** (open a menu now,\n defer it, or ignore the press): make the step a Mealy function returning\n `{ state, output }`, so every decision lives in one place.\n- **Long-lived controllers that log or notify on change**: have `send` return\n the previous state too, so the caller acts only on the change that happened\n (log on `starting -> playing`, not on every event).\n- **Classes holding resources** (sockets, timers, watchdogs): give each\n resource to exactly one state and release it in one `leave(previous, next)`\n step; guard `if (next === this.state) return` because leave callbacks can\n re-enter (`onDisconnect` calling `stop()`).\n- **Testing async controllers**: move the React controller into its own hook\n with the async work injected, so `renderHook` can drive stale, replacement\n and Strict Mode sequences. In React Native Testing Library, start a press\n without awaiting it to observe the pending state, then resolve inside\n `await act(...)`.\n- **Dismissals name what they dismiss** (outside click, escape): otherwise the\n listener of the menu that just closed can close the menu that replaced it.\n\n### Placement and lint\n\n- Put the reducer beside the code that runs it when a new module costs a\n network request or a build allowlist entry (bundler-free static sites), and\n in Swift in a file already compiled into the app target, to avoid an Xcode\n project edit.\n- A reducer can exceed Biome's cognitive-complexity limit; one type guard such\n as `inAttempt(state, attempt, ...statuses)` usually brings it back.\n\n## Swift\n\n```swift\nenum Upload: Equatable {\n case idle\n case uploading(progress: Double)\n case failed(message: String)\n case done(url: URL)\n\n func handling(_ event: UploadEvent) -> Upload {\n switch (self, event) {\n case (.idle, .start), (.failed, .start): return .uploading(progress: 0)\n case (.uploading, .progress(let p)): return .uploading(progress: p)\n case (.uploading, .finish(let url)): return .done(url: url)\n case (.uploading, .fail(let message)): return .failed(message: message)\n default: return self\n }\n }\n}\n```\n\nAvoid a `default` that hides a new case where the compiler could check it:\nswitch on `self` first and handle every case.\n\n## Kotlin\n\nA `sealed interface State` with `data object Idle : State` and\n`data class Failed(val error: Throwable) : State`, and a\n`fun State.on(event: Event): State = when (this) { ... }` with no `else`\nbranch, so a new state fails to compile until it is handled.\n\n## Python\n\n```python\nfrom dataclasses import dataclass\nfrom typing import assert_never\n\n@dataclass(frozen=True)\nclass Idle: ...\n@dataclass(frozen=True)\nclass Running:\n job_id: str\n@dataclass(frozen=True)\nclass Failed:\n error: str\n\nState = Idle | Running | Failed\n\ndef transition(state: State, event: Event) -> State:\n match state, event:\n case Idle(), Start(job_id=job_id):\n return Running(job_id)\n case Running(), Fail(error=error):\n return Failed(error)\n case _:\n return state\n```\n\nWhere a plain enum suffices (no per-state data), use `enum.Enum` and an\n`ALLOWED: dict[State, frozenset[State]]` table.\n\n## Go\n\nA `type State int` with `const` values and a `String()` method, a\n`func (s State) On(e Event) (State, error)` that returns an error for an\nillegal transition, and an `exhaustive` lint if the repository runs one.\n\n## Shell\n\nOne `state` variable and a `case \"$state\" in` loop instead of several\n`done=0`/`failed=1` variables; print the state when the script exits early.\n"
|
|
34
35
|
},
|
|
36
|
+
"optimize-ci": {
|
|
37
|
+
"references/lessons.md": "# CI lessons\n\nCross-repository findings from CI passes, newest first. Each names the\nrepository and the PRs it came from; recheck before relying on one.\n\n## Split the long serial file list out of a catch-all job\n\na2f0/tearleads #3333. A job running \"the remaining package tests\" finished\nlast in 60 of 80 runs (median 18.6 minutes): one package's end-to-end suite ran\n1158 s of serial files inside it. Giving that package five matrix shards,\nbalanced with Bun's `--timings` from per-file times read out of uncached job\nlogs, took the catch-all job from 20.9 to 7.4 minutes and the whole uncached\nrun from 21 to 14. The slowest shard came in about 25% over its prediction;\nplan shard counts with that margin. Bun keeps files in path order within a\ntimed shard, so a long file only splits usefully at higher shard counts, and\nno shard is shorter than its longest file.\n\n## Playwright shards by test count, not time\n\na2f0/tearleads #3332. Playwright 1.64 deals whole spec files to shards by test\ncount in project-then-file order, so a shard full of fast tests finishes early:\nthree shards left the slowest with 46% of the suite, four with 33%. Four\nshards took the browser suite from a 13.1 minute median to about 6 minutes.\n`playwright test --list --shard=i/N --reporter=json` names each shard's exact\ntests before any build, so a shard can install only the browsers its projects\nuse (63 s to 23 s for Chromium-only shards). The same shard's time varied from\n2.9 to 4.7 minutes with identical inputs: read the slowest shard as a range.\n\n## Environment-conditional config splits local and CI static analysis\n\na2f0/tearleads #3332. A Playwright config that added a reporter only when `CI`\nwas set let Knip's Playwright plugin see the reporter on CI but not locally, so\nKnip passed locally and failed on CI with a redundant-entry hint. Keep config\nthe same in every environment, or run static checks with `CI=true` as well.\n\n## Version bumps and lockfiles defeat path filters and task keys\n\na2f0/tearleads #3331 and #3334. Every pull request bumped package versions and\nrefreshed the lockfile, so lanes meant only for native or infrastructure\nchanges ran in 72 to 74 of 80 runs. Two fixes helped:\n\n- Treat a lockfile diff that changes only workspace `version` fields as\n touching nothing, and count anything unparseable as changed.\n- Key a task on exactly what it reads. An iOS compile check that synced a\n placeholder page instead of the web build, and moved from a root task to a\n package task, cut its key changes from 277 to 18 per 300 merges, and its\n job from 12.5 minutes to a 30 s replay.\n\nIn Turbo, a root (`//#`) task always hashes the root `package.json`, and a\npackage task with explicit inputs always hashes its own manifest. Keep the\nmanifest in a native key when the sync tool runs manifest hook scripts, as\n`cap sync` does.\n\n## Prove a build cache with a warm run before keeping it\n\na2f0/tearleads #3334. An exact-key Xcode DerivedData restore on the runner's\nXcode 16.4 still rebuilt all 1622 object files: 690 MB of cache for no gain,\nwhile the same restore on a newer local Xcode cut 190 s to 31 s. Measure a\ncold run that saves and a warm run that restores before shipping any cache.\n\n## More workers on the same cores is not a split\n\na2f0/tearleads #3335. Raising the TLC model checker from two to four JVMs at a\ntime on 4-vCPU runners made each run at least 1.5 times slower, so the job\nfell only to the total work divided by four, and runner speed varied about\ntwofold between uncached runs on the default branch (491 to 1008 s): one run\ncould not show the change helped. Once total work bounds a job, split it\nacross runners, longest item first, and measure against many baseline runs.\nA scheduling hint such as a recorded-durations file must ignore stale entries,\nas Bun's `--timings` does: failing on a renamed item turns every rename\nelsewhere into a CI failure.\n\n## Merge policy can serialize a CI round\n\na2f0/tearleads, 2026-11-26. A version check that required each branch to carry\nthe default branch's version of every package made each merge force every\nqueued pull request to integrate and rerun its full CI, so five pull requests\nmerged one CI run at a time. A one-off push-gate break on the default branch\n(stale ignore entries left by a merge) blocked every push until its repair\nmerged. Count merge-queue time in a round's estimate, and let the pull request\nthat repairs a shared gate merge first.\n",
|
|
38
|
+
"agents/openai.yaml": "interface:\n display_name: \"Optimize CI\"\n short_description: \"Cut CI wall-clock time in measured rounds without checking less\"\n default_prompt: \"Use $optimize-ci to make this repository's CI faster: measure which job holds the wall clock, change one lever, prove it on CI, and ship.\"\n"
|
|
39
|
+
},
|
|
35
40
|
"performance-pass": {
|
|
36
41
|
"references/lessons.md": "# Performance lessons\n\nCross-repository findings from performance passes, newest first. Each names\nthe repository and PR it came from; recheck before relying on one.\n\n## Layers that change nothing until used can wait for first use\n\nskyline built its colour-trial layer, which reads every vertex of every\nbuilding, before the first frame, though its shaders install only when colour,\na previewed time or a celebration is used. Making it on first use (and before\na celebration rewrites the greys it reads) took its 160 to 270 ms off the\nfirst frame, pixel-identical in seven before/after interaction shots.\n\n## Unbundled ES module graphs pay one round trip per import level\n\nskyline (a2f0/skyline) ships tsc output without a bundler, so the viewer's\nfirst frame waited on a chain seven requests deep. Listing the graph at build\ntime and preloading it with `modulepreload` from the mounting code moved\nnetwork-done from 1471 to 833 ms and the ready median from 2369 to 1763 ms at\n40 ms / 20 Mbps (5204 to 4514 ms on the slow profile), pixel-identical with\nthe random stars hidden. Generate the list from the built files so it cannot\ndrift, leave out modules the host may replace, and expect a host-bundle size\nbudget to need room for the preloading code.\n\n## Seeded randomness still drifts when load order changes\n\nThree.js draws object UUIDs from `Math.random`, so a seeded page that builds\nits scene earlier or later relative to random decoration (skyline's stars)\nshows that decoration elsewhere. Hide the decoration with `shot --hide` and\ndiff the rest; two base shots must still diff to zero first.\n",
|
|
37
42
|
"agents/openai.yaml": "interface:\n display_name: \"Performance Pass\"\n short_description: \"Speed up loading in measured rounds without changing output\"\n default_prompt: \"Use $performance-pass to make this page load faster without changing what it shows: measure, change one thing, prove fidelity, measure again, and ship.\"\n"
|