@a2f0/agent-tool 0.1.75 → 0.1.77

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 CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@a2f0/agent-tool",
3
- "version": "0.1.75",
3
+ "version": "0.1.77",
4
4
  "packageManager": "bun@1.4.4",
5
5
  "type": "module",
6
6
  "description": "Portable cross-agent review, PR workflows, and shared skills",
@@ -13,6 +13,8 @@ not a win.
13
13
  ## Measuring
14
14
 
15
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`.
16
18
 
17
19
  | Command | Shows |
18
20
  | --- | --- |
@@ -42,13 +44,17 @@ A lane is a job name without shard counters, so `Test (api 1/3)` and
42
44
  sets that job's length; give it its own matrix entries. Balance shards by
43
45
  measured time, not file count (Bun's `--shard` with `--timings`,
44
46
  Playwright's `--shard` from spec durations): a count split of uneven files
45
- is lopsided. No shard is shorter than its longest file, so split that file
46
- when its cases are independent.
47
+ is lopsided. Bun falls back to a count split without a word when the
48
+ timings file is missing, so let a policy test require it. No shard is
49
+ shorter than its longest file, so split that file when its cases are
50
+ independent.
47
51
  - Use the cores the runner has. Check effective parallelism: test runners'
48
52
  CI defaults (Playwright uses half the cores), tool flags (TLC
49
53
  `-workers 1`), and pool sizes. Raise them only with measured memory
50
54
  headroom, and keep timing-sensitive end-to-end suites on their own runners
51
- rather than crowding one.
55
+ rather than crowding one. Time each item before and after: when more
56
+ workers only make each item slower, total work bounds the job, and the
57
+ lever is splitting it across runners.
52
58
  - Schedule longest first in any pool, so a long item never starts last.
53
59
  - Cache what every run rebuilds: toolchains, browsers, package stores,
54
60
  compiler output (Xcode DerivedData and SwiftPM, Gradle), and task results.
@@ -71,8 +77,9 @@ A lane is a job name without shard counters, so `Test (api 1/3)` and
71
77
  merge, and report the change in median and p90 wall clock. Start the next
72
78
  round from step 3 with the new top lane.
73
79
  7. Learn. Repository-specific findings go in that repository's guidance.
74
- Cross-repository lessons go in [references/lessons.md](references/lessons.md)
75
- here, by PR.
80
+ Cross-repository lessons go in agent-tool's
81
+ `skills/optimize-ci/references/lessons.md` by PR, naming the repository and
82
+ PR; [the installed copy](references/lessons.md) is read-only.
76
83
 
77
84
  ## Pitfalls
78
85
 
@@ -91,8 +98,26 @@ A lane is a job name without shard counters, so `Test (api 1/3)` and
91
98
  - Turbo buffers a task's output until it ends, so log timestamps show
92
99
  completion, not progress. Use the test runner's own case durations.
93
100
  - Turning a job into a matrix renames its check (`Web E2E` becomes
94
- `Web E2E (1/3)`). Update branch protection, rulesets, and the merge helper's
95
- required checks together, or require an aggregate gate job instead.
101
+ `Web E2E (1/3)`), and so does moving it into a reusable workflow, which
102
+ prefixes the caller's job name (`models / Protocol models`). Update branch
103
+ protection, rulesets, and the merge helper's required checks together, or
104
+ require an aggregate gate job instead.
96
105
  - Changing a shard count reshuffles which files share a worker; with test
97
106
  isolation off, that can surface leaks between files. Run every new shard
98
107
  composition before pushing.
108
+ - Config chosen on `CI` (reporters, plugins, entries) looks different to
109
+ static analysis locally and on CI, so a check passes locally and fails on CI.
110
+ Keep config the same everywhere, or run those checks with `CI=true` too.
111
+ - A recorded-durations file only orders and balances work. It must ignore
112
+ entries for items that no longer exist and weight unknown ones, or a rename
113
+ in any pull request fails CI on a scheduling hint.
114
+ - Merge policy is part of the wall clock: a check that forces queued pull
115
+ requests to integrate after every merge reruns their CI one at a time.
116
+
117
+ ## Ownership
118
+
119
+ agent-tool (`a2f0/agent-tool`) owns this skill at `skills/optimize-ci/` and the
120
+ `ci timings` command at `src/ci/`, with its tests beside it; `agent-tool skills
121
+ install --apply` installs it in each adopting repository. Change it there,
122
+ never in an installed copy. A repository's CI layout, required checks, and
123
+ measured baselines belong in its own docs.
@@ -1,30 +1,112 @@
1
1
  # CI lessons
2
2
 
3
- Cross-repository findings from CI passes, newest first. Each names the
4
- repository and PR it came from; recheck before relying on one.
5
-
6
- ## A catch-all job can hide the whole critical path
7
-
8
- tearleads (a2f0/tearleads, baseline 2026-11-26) ran its long suites in their own
9
- sharded jobs, but the job holding "the remaining package tests" finished last
10
- in 60 of 80 runs at a median of 18.6 minutes. `ci timings --job` showed why: one
11
- package's end-to-end suite ran 1158 s of serial files inside it, while every
12
- sharded job finished in under 9 minutes. Look inside the slowest job before
13
- adding shards elsewhere.
14
-
15
- ## Version bumps defeat path filters and task caches
16
-
17
- The same repository bumps every changed package's version and refreshes its
18
- lockfile in every pull request. Its path classifier treated any lockfile change
19
- as touching everything, so lanes meant to run only for native or
20
- infrastructure changes ran in 72 to 74 of 80 runs, and a browser suite whose
21
- inputs included every package manifest executed in 95% of runs. When a lane
22
- that should be rare has a high `overThresholdShare`, look for a file that every
23
- pull request rewrites.
24
-
25
- ## Tool defaults leave runner cores idle
26
-
27
- On 4-vCPU runners, Playwright's CI default of half the cores ran 282 tests on 2
28
- workers, and the TLC model checker ran each model with `-workers 1`, two models
29
- at a time. Read the effective parallelism of every long step before buying
30
- bigger runners.
3
+ Cross-repository findings from CI passes, newest source pull request first,
4
+ with findings about a whole round after them. Each names the repository and the
5
+ PRs it came from; recheck before relying on one.
6
+
7
+ ## Balanced shards need their timings file
8
+
9
+ a2f0/tearleads #3354. Moving four Bun suites from round-robin to `--timings`
10
+ shards brought each suite's shards within 9% of each other, and three app
11
+ shards replaced two (slowest 9.3 to 6.5 minutes). Bun splits by file count,
12
+ without a word, when the timings file is missing, and costs a file the table
13
+ does not list at the table's median, so a policy test should fail any sharded
14
+ suite without one. A Turbo cache replay repeats the original run's durations:
15
+ deduplicate timing samples by task hash before building a table. Balanced
16
+ shards on a slower runner can still take longer than the old split did, so
17
+ judge balance by the spread within a run, not by one run against another.
18
+
19
+ ## Faster shards expose timing races
20
+
21
+ a2f0/tearleads #3352. Sharding changed when a browser test's requests overlapped
22
+ with the app's own startup syncs, and a wait that matched "the next request to
23
+ this path" resolved on the app's request instead of the test's; the test then
24
+ failed in about 3 of 5 runs under load. The fix matched on the request's own
25
+ object, with no timeout or retry change. Repair a race a CI change exposes at its
26
+ source in its own pull request, then merge the base into any pull request it
27
+ failed: a rerun replays the old merge commit without the fix.
28
+
29
+ ## Split across runners when work bounds a job
30
+
31
+ a2f0/tearleads #3335 and #3350. Raising the TLC model checker from two to four
32
+ JVMs at a time on 4-vCPU runners made each run at least 1.5 times slower, so
33
+ the job fell only to the total work divided by four. Three runners at two runs
34
+ each, longest first, took the slowest shard to 365 s against a 689 s median.
35
+ Runner speed varied about twofold between uncached runs on the default branch
36
+ (491 to 1008 s), so one run could not show either change helped: measure
37
+ against many baseline runs. A scheduling hint such as a recorded-durations file
38
+ must ignore stale entries, as Bun's `--timings` does, or a rename anywhere
39
+ fails CI. Moving the job into a reusable workflow to stay under a workflow
40
+ line budget renamed its checks (`models / ...`).
41
+
42
+ ## Prove a build cache with a warm run before keeping it
43
+
44
+ a2f0/tearleads #3334. An exact-key Xcode DerivedData restore on the runner's
45
+ Xcode 16.4 still rebuilt all 1622 object files: 690 MB of cache for no gain,
46
+ while the same restore on a newer local Xcode cut 190 s to 31 s. Measure a
47
+ cold run that saves and a warm run that restores before shipping any cache.
48
+
49
+ ## Version bumps and lockfiles defeat path filters and task keys
50
+
51
+ a2f0/tearleads #3331 and #3334. Every pull request bumped package versions and
52
+ refreshed the lockfile, so lanes meant only for native or infrastructure
53
+ changes ran in 72 to 74 of 80 runs. Two fixes helped:
54
+
55
+ - Treat a lockfile diff that changes only workspace `version` fields as
56
+ touching nothing, and count anything unparseable as changed.
57
+ - Key a task on exactly what it reads. An iOS compile check that synced a
58
+ placeholder page instead of the web build, and moved from a root task to a
59
+ package task, cut its key changes from 277 to 18 per 300 merges, and its
60
+ job from 12.5 minutes to a 30 s replay.
61
+
62
+ In Turbo, a root (`//#`) task always hashes the root `package.json`, and a
63
+ package task with explicit inputs always hashes its own manifest. Keep the
64
+ manifest in a native key when the sync tool runs manifest hook scripts, as
65
+ `cap sync` does.
66
+
67
+ ## Split the long serial file list out of a catch-all job
68
+
69
+ a2f0/tearleads #3333. A job running "the remaining package tests" finished
70
+ last in 60 of 80 runs (median 18.6 minutes): one package's end-to-end suite ran
71
+ 1158 s of serial files inside it. Giving that package five matrix shards,
72
+ balanced with Bun's `--timings` from per-file times read out of uncached job
73
+ logs, took the catch-all job from 20.9 to 7.4 minutes and the whole uncached
74
+ run from 21 to 14. The slowest shard came in about 25% over its prediction;
75
+ plan shard counts with that margin. Bun keeps files in path order within a
76
+ timed shard, so a long file only splits usefully at higher shard counts, and
77
+ no shard is shorter than its longest file.
78
+
79
+ ## Playwright shards by test count, not time
80
+
81
+ a2f0/tearleads #3332. Playwright 1.64 deals whole spec files to shards by test
82
+ count in project-then-file order, so a shard full of fast tests finishes early:
83
+ three shards left the slowest with 46% of the suite, four with 33%. Four
84
+ shards took the browser suite from a 13.1 minute median to about 6 minutes.
85
+ `playwright test --list --shard=i/N --reporter=json` names each shard's exact
86
+ tests before any build, so a shard can install only the browsers its projects
87
+ use (63 s to 23 s for Chromium-only shards). The same shard's time varied from
88
+ 2.9 to 4.7 minutes with identical inputs: read the slowest shard as a range.
89
+
90
+ ## Environment-conditional config splits local and CI static analysis
91
+
92
+ a2f0/tearleads #3332. A Playwright config that added a reporter only when `CI`
93
+ was set let Knip's Playwright plugin see the reporter on CI but not locally, so
94
+ Knip passed locally and failed on CI with a redundant-entry hint. Keep config
95
+ the same in every environment, or run static checks with `CI=true` as well.
96
+
97
+ ## The round as a whole
98
+
99
+ a2f0/tearleads #3331 to #3354, 2026-11-26. Pull-request runs that carried the
100
+ round's changes took 6.9 to 10 minutes to the gate, against a 19.1 minute
101
+ median before; the lane finishing last moved from one catch-all test job (60
102
+ of 80 runs) to a spread of model, native, and browser lanes. Two things outside
103
+ the pipeline cost the most time:
104
+
105
+ - A version check that required each branch to carry the default branch's
106
+ version of every package made each merge force every queued pull request to
107
+ integrate and rerun its full CI, so pull requests merged one CI run at a time.
108
+ - A one-off push-gate break on the default branch (stale ignore entries left by
109
+ a merge) blocked every push until its repair merged.
110
+
111
+ Count merge-queue time in a round's estimate, and let the pull request that
112
+ repairs a shared gate merge first.
package/src/ci/command.ts CHANGED
@@ -4,7 +4,7 @@ import { runRead } from "../git/prContext";
4
4
  import { assert, json, option, output, repository } from "../workflows/core";
5
5
  import { parseJobLog, runSteps, summarizeRuns, type TimedJob, type TimedRun } from "./timings";
6
6
 
7
- export const CI_TIMINGS_USAGE = `Usage: agent-tool ci timings [--workflow <file|name|id>] [--branch <name>] [--event <event>] [--limit <n>] [--gate <job>] [--threshold <minutes>]
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
8
  agent-tool ci timings --run <run-id> [--min-seconds <n>]
9
9
  agent-tool ci timings --job <job-id> [--top <n>]
10
10
 
@@ -91,6 +91,8 @@ export function ciTimingsCommand(argv: string[]): number {
91
91
  const repo = repository().nameWithOwner;
92
92
  const runs = listRuns(repo, { workflow, branch, event }, count)
93
93
  .map(item => ({ ...item, jobs: item.attempt > 1 ? [] : jobs(repo, item.id, false) }));
94
- output({ repo, workflow: workflow ?? null, branch: branch ?? null, event: event ?? null, gate: gate ?? null, ...summarizeRuns(runs, { gate, thresholdMinutes }) });
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 });
95
97
  return 0;
96
98
  }
package/src/ci/timings.ts CHANGED
@@ -46,8 +46,8 @@ export interface JobStats {
46
46
 
47
47
  export interface TimingSummary {
48
48
  runs: number;
49
- /** Runs left out: re-run attempts mix timestamps of several attempts, and runs without the named gate job. */
50
- excluded: { reruns: number; missingGate: 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
51
  thresholdMinutes: number;
52
52
  /** Run creation to the gate job's end, or to the last job's end without a gate. */
53
53
  wallMinutes: Spread;
@@ -58,23 +58,33 @@ export interface TimingSummary {
58
58
  jobs: JobStats[];
59
59
  }
60
60
 
61
- /** Summarize successful runs of one workflow. A gate job, when named, ends the wall clock and is left out of `lastToFinish`. */
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. When
64
+ * most jobs ended after the gate started, the gate is taken to poll them, and the count uses its end.
65
+ */
62
66
  export function summarizeRuns(runs: TimedRun[], options: { gate?: string; thresholdMinutes: number }): TimingSummary {
63
- const excluded = { reruns: 0, missingGate: 0 };
67
+ const excluded = { reruns: 0, noJobs: 0, missingGate: 0 };
64
68
  const walls: number[] = [], firstLags: number[] = [];
65
69
  const last = new Map<string, number>();
66
70
  const perJob = new Map<string, { durations: number[]; lags: number[] }>();
67
71
  for (const run of runs) {
68
72
  if (run.attempt > 1) { excluded.reruns++; continue; }
69
73
  const jobs = executedJobs(run.jobs);
70
- if (!jobs.length) continue;
74
+ if (!jobs.length) { excluded.noJobs++; continue; }
71
75
  const gate = options.gate === undefined ? undefined : jobs.find(job => job.name === options.gate);
72
76
  if (options.gate !== undefined && !gate) { excluded.missingGate++; continue; }
73
77
  const work = jobs.filter(job => job !== gate);
74
78
  const end = gate?.completedAt ?? work.reduce((latest, job) => job.completedAt > latest ? job.completedAt : latest, work[0]!.completedAt);
75
79
  walls.push(minutesBetween(run.createdAt, end));
76
80
  firstLags.push(Math.max(0, minutesBetween(run.createdAt, jobs.reduce((first, job) => job.startedAt < first ? job.startedAt : first, jobs[0]!.startedAt)) * 60));
77
- const finisher = work.reduce<(typeof work)[number] | undefined>((latest, job) => !latest || job.completedAt > latest.completedAt ? job : latest, undefined);
81
+ // A gate that `needs` its jobs starts after they end, so jobs that ended after it started (optional
82
+ // lanes, post-gate deploys) did not hold it. A gate that polls starts early: when most jobs ended after
83
+ // it started, it is taken to poll, and the jobs that ended before it did are the ones it waited for.
84
+ const beforeStart = gate ? work.filter(job => job.completedAt <= gate.startedAt) : work;
85
+ const polls = gate !== undefined && beforeStart.length * 2 < work.length;
86
+ const awaited = polls ? work.filter(job => job.completedAt <= gate.completedAt) : beforeStart;
87
+ const finisher = awaited.reduce<(typeof work)[number] | undefined>((latest, job) => !latest || job.completedAt > latest.completedAt ? job : latest, undefined);
78
88
  if (finisher) last.set(lane(finisher.name), (last.get(lane(finisher.name)) ?? 0) + 1);
79
89
  for (const job of work) {
80
90
  const entry = perJob.get(job.name) ?? { durations: [], lags: [] };
@@ -144,7 +154,9 @@ export function parseJobLog(text: string): LogTimings {
144
154
  const line = lines[index]!;
145
155
  if (line.startsWith("##[group]")) {
146
156
  const name = line.slice("##[group]".length).trim();
147
- const next = lines.slice(index + 1).find(candidate => candidate.trim() !== "")?.trim() ?? "";
157
+ let ahead = index + 1;
158
+ while (ahead < lines.length && lines[ahead]!.trim() === "") ahead++;
159
+ const next = lines[ahead]?.trim() ?? "";
148
160
  const cache = next.match(CACHE)?.[1] as LogTask["cache"] | undefined;
149
161
  const parent = [...stack].reverse().find(entry => entry.kind === "task");
150
162
  if (cache) { tasks.push({ task: name, cache }); stack.push({ kind: "task", name, cached: cache === "hit" }); }
@@ -6,7 +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.\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 [references/lessons.md](references/lessons.md)\n here, by PR.\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",
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. Bun falls back to a count split without a word when the\n timings file is missing, so let a policy test require it. No shard is\n shorter than its longest file, so split that file when its cases are\n 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. Time each item before and after: when more\n workers only make each item slower, total work bounds the job, and the\n lever is splitting it across runners.\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)`), and so does moving it into a reusable workflow, which\n prefixes the caller's job name (`models / Protocol models`). Update branch\n protection, rulesets, and the merge helper's required checks together, or\n 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",
10
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",
11
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",
12
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",
@@ -34,7 +34,7 @@ export const BUNDLED_SKILL_REFERENCES: Readonly<Record<string, Readonly<Record<s
34
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"
35
35
  },
36
36
  "optimize-ci": {
37
- "references/lessons.md": "# CI lessons\n\nCross-repository findings from CI passes, newest first. Each names the\nrepository and PR it came from; recheck before relying on one.\n\n## A catch-all job can hide the whole critical path\n\ntearleads (a2f0/tearleads, baseline 2026-11-26) ran its long suites in their own\nsharded jobs, but the job holding \"the remaining package tests\" finished last\nin 60 of 80 runs at a median of 18.6 minutes. `ci timings --job` showed why: one\npackage's end-to-end suite ran 1158 s of serial files inside it, while every\nsharded job finished in under 9 minutes. Look inside the slowest job before\nadding shards elsewhere.\n\n## Version bumps defeat path filters and task caches\n\nThe same repository bumps every changed package's version and refreshes its\nlockfile in every pull request. Its path classifier treated any lockfile change\nas touching everything, so lanes meant to run only for native or\ninfrastructure changes ran in 72 to 74 of 80 runs, and a browser suite whose\ninputs included every package manifest executed in 95% of runs. When a lane\nthat should be rare has a high `overThresholdShare`, look for a file that every\npull request rewrites.\n\n## Tool defaults leave runner cores idle\n\nOn 4-vCPU runners, Playwright's CI default of half the cores ran 282 tests on 2\nworkers, and the TLC model checker ran each model with `-workers 1`, two models\nat a time. Read the effective parallelism of every long step before buying\nbigger runners.\n",
37
+ "references/lessons.md": "# CI lessons\n\nCross-repository findings from CI passes, newest source pull request first,\nwith findings about a whole round after them. Each names the repository and the\nPRs it came from; recheck before relying on one.\n\n## Balanced shards need their timings file\n\na2f0/tearleads #3354. Moving four Bun suites from round-robin to `--timings`\nshards brought each suite's shards within 9% of each other, and three app\nshards replaced two (slowest 9.3 to 6.5 minutes). Bun splits by file count,\nwithout a word, when the timings file is missing, and costs a file the table\ndoes not list at the table's median, so a policy test should fail any sharded\nsuite without one. A Turbo cache replay repeats the original run's durations:\ndeduplicate timing samples by task hash before building a table. Balanced\nshards on a slower runner can still take longer than the old split did, so\njudge balance by the spread within a run, not by one run against another.\n\n## Faster shards expose timing races\n\na2f0/tearleads #3352. Sharding changed when a browser test's requests overlapped\nwith the app's own startup syncs, and a wait that matched \"the next request to\nthis path\" resolved on the app's request instead of the test's; the test then\nfailed in about 3 of 5 runs under load. The fix matched on the request's own\nobject, with no timeout or retry change. Repair a race a CI change exposes at its\nsource in its own pull request, then merge the base into any pull request it\nfailed: a rerun replays the old merge commit without the fix.\n\n## Split across runners when work bounds a job\n\na2f0/tearleads #3335 and #3350. Raising the TLC model checker from two to four\nJVMs at a time on 4-vCPU runners made each run at least 1.5 times slower, so\nthe job fell only to the total work divided by four. Three runners at two runs\neach, longest first, took the slowest shard to 365 s against a 689 s median.\nRunner speed varied about twofold between uncached runs on the default branch\n(491 to 1008 s), so one run could not show either change helped: measure\nagainst many baseline runs. A scheduling hint such as a recorded-durations file\nmust ignore stale entries, as Bun's `--timings` does, or a rename anywhere\nfails CI. Moving the job into a reusable workflow to stay under a workflow\nline budget renamed its checks (`models / ...`).\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## 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## 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## The round as a whole\n\na2f0/tearleads #3331 to #3354, 2026-11-26. Pull-request runs that carried the\nround's changes took 6.9 to 10 minutes to the gate, against a 19.1 minute\nmedian before; the lane finishing last moved from one catch-all test job (60\nof 80 runs) to a spread of model, native, and browser lanes. Two things outside\nthe pipeline cost the most time:\n\n- A version check that required each branch to carry the default branch's\n version of every package made each merge force every queued pull request to\n integrate and rerun its full CI, so pull requests merged one CI run at a time.\n- A one-off push-gate break on the default branch (stale ignore entries left by\n a merge) blocked every push until its repair merged.\n\nCount merge-queue time in a round's estimate, and let the pull request that\nrepairs a shared gate merge first.\n",
38
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
39
  },
40
40
  "performance-pass": {