@a2f0/agent-tool 0.1.73 → 0.1.75
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/README.md +8 -7
- package/package.json +1 -1
- package/skills/optimize-ci/SKILL.md +98 -0
- package/skills/optimize-ci/agents/openai.yaml +4 -0
- package/skills/optimize-ci/references/lessons.md +30 -0
- package/skills/performance-pass/SKILL.md +1 -1
- package/skills/take-screenshots/SKILL.md +103 -0
- package/skills/take-screenshots/agents/openai.yaml +4 -0
- package/skills/take-screenshots/references/adding-capture.md +121 -0
- package/src/ci/command.ts +96 -0
- package/src/ci/timings.ts +174 -0
- package/src/cli.ts +15 -2
- package/src/perf/graph.ts +13 -3
- package/src/permissions/catalog.ts +3 -1
- package/src/screenshots/build.ts +4 -3
- package/src/screenshots/store/capture.ts +317 -0
- package/src/screenshots/store/clones.ts +145 -0
- package/src/screenshots/store/command.ts +317 -0
- package/src/screenshots/store/git.ts +14 -0
- package/src/screenshots/store/link.ts +201 -0
- package/src/screenshots/store/lock.ts +94 -0
- package/src/screenshots/store/namespace.ts +311 -0
- package/src/screenshots/store/record.ts +157 -0
- package/src/screenshots/store/store.ts +47 -0
- package/src/screenshots/store/targets.ts +68 -0
- package/src/skills/bundled.ts +11 -1
- package/src/system/checkouts.ts +29 -7
package/src/skills/bundled.ts
CHANGED
|
@@ -6,12 +6,14 @@ 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
|
-
"
|
|
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",
|
|
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",
|
|
12
13
|
"ship-pr": "---\nname: ship-pr\ndescription: Complete an authorized commit, independent review, repair, PR, CI, and squash-merge workflow for a GitHub repository.\n---\n\n# Ship PR\n\nUse the installed `agent-tool`. Read repository guidance and policy first;\nvalidation, versioning, package management, and hook bodies remain project\nconcerns. Use shared branch, hook, check, cleanup, and release commands where\nconfigured; keep application-specific commands in repository guidance. Shipping authorizes this workflow within the user's stated scope.\nPreserve unrelated edits and honor requested stopping points such as open-PR\nonly, report-only review, or keeping the feature branch.\n\nUse `agent-tool run --label <check> -- <command> [args...]` for noisy setup,\nvalidation, builds, and hook-running Git commands. It preserves exit status and\ncomplete private logs, prints one success receipt, and shows a bounded failure\ntail. Inspect more with `agent-tool logs <log> --max-bytes 8192 --tail-lines 80`\nor a targeted search; never dump an entire suite log or pipe checks into `tail`.\nThe receipt proves process completion, not absence of warnings: inspect required\nwarning, coverage, timing, or artifact evidence before accepting a check. Keep\nmachine-readable receipts and review findings visible by running `versions\nprepare`, `review`, `repo base-health`, and other commands whose output drives a\ndecision directly. Prefer documented compact test reporters when they preserve\nrequired evidence; do not reduce test scope, skip checks, silence warnings, or\nmask failures. Start servers, watchers, and other long-running processes with\n`agent-tool proc start --label <name> -- <command>`, never a backgrounded shell\ncommand, so they can be found and stopped.\n\n1. Start from the base branch's health: `agent-tool repo base-health` (with\n `--branch <base-branch>` for another base). `green`, `pending`, and `no-ci`\n need nothing more; report `no-ci` as missing CI on pushes. When it is\n `red`, read the failing jobs' logs (`gh run view <run-id> --log-failed`\n through `agent-tool run`) and relate them to the merges in\n `breakingRange`. Broken logic from combined merges: fix it and add the test\n that would have caught the combination. A flaky or timing-dependent test:\n remove the race, ordering dependence, or shared state. Infrastructure or an\n outside service: record it; rerun only when the log shows the cause was\n external. Never retry until green, skip, or loosen an assertion. When\n `openRepairs` lists a PR, do not duplicate it. Otherwise ship the repair\n through this workflow as its own PR, naming the failing run in its body,\n ahead of the requested change; when the change touches the same code, make\n the repair a separate commit in that PR and say so in its description. A\n red base does not block an unrelated change; stop only when the change\n cannot be validated without the repair. A PR failure with the same job and\n error as on the base is repaired on the base. Reverting the breaking merge\n is allowed when the fix is not small and the break blocks a deploy or\n publish; the revert names the merge and the follow-up that restores it.\n2. Finish the requested change on a feature branch. Use\n `agent-tool branch create <branch> --base <base-branch> --remote <remote>`\n from a clean checkout; it fetches and pins the base, checks naming policy and\n collisions, and creates without a local upstream. Use `branch check` with\n explicit destination names in CI or hooks. Before pushing, validate with the\n repository's push gate and the tests that target the changed code, not the\n full suite: CI runs everything and is the authority. Commit only the\n intended files.\n3. Use `agent-tool repo context --fetch` to resolve the PR's base repository\n and branch, or the default branch when no PR exists, and fetch its exact base.\n Record the returned base/head identities. Integrate the fetched base\n using the repository's normal workflow, resolving conflicts without losing\n user work. If project policy versions packages, prepare versions against the\n pinned base after every integration or repair and before each review, using\n the project's commands or `agent-tool versions prepare <base-oid>`, which\n commits bumped manifests and the refreshed lockfile.\n `agent-tool versions resolve-conflicts` resolves conflicts confined to\n version fields. Review the resulting committed HEAD with an independent\n reviewer using the bundled cross-agent-review skill. Repair blocking findings\n and review every changed HEAD again. Review failure blocks shipping. One\n change keeps a review: after a clean review, a new HEAD that only integrated\n the base and prepared versions (as when another PR took the same version\n first). When `agent-tool review carry <reviewed-head> <new-head>` exits 0\n with `ok: true`, the earlier clean review stands, and the new HEAD is the\n reviewed head from then on; report the review as carried, giving the\n reviewed head and the command's JSON output. Every other changed HEAD,\n including one the command rejects, gets an independent review, and CI\n still runs on the new HEAD.\n4. Run `agent-tool branch push <reviewed-head> --remote <remote>` through\n normal hooks; it verifies local and remote identity afterward. If a hook\n changed content or HEAD, review that result.\n Open the PR using the open-pr skill, or update the existing PR as needed.\n5. Allow configured review bots time to respond, then use\n `agent-tool pr threads list` to fetch review threads and all comments. Follow repository policy for feedback: fix valid findings,\n reply with `pr threads reply <comment-id>` (body file or stdin), and use\n `pr threads resolve <thread-id>` only for fully addressed findings.\n Validate, commit, push, and independently review every feedback or CI repair.\n Wait with `agent-tool pr checks --wait --head <reviewed-head>`, whose limit\n defaults to `agent-tool.json` `merge.checksTimeoutSeconds`. When a job\n fails, read its log with `agent-tool pr logs --head <reviewed-head>`, fix it\n in a new commit, review it, push, and wait on the new head. A base that\n moved (`behind: true`) needs no integration unless GitHub reports a\n conflict, `versions check` fails against the live base, or the repository\n sets `merge.requireStrictBaseFreshness`; under that policy the wait stops\n early, so cancel the stale head's CI with\n `agent-tool pr cancel-runs --head <reviewed-head>`, then integrate,\n validate, review (or carry the review, as in step 3), push, and wait again.\n Then run\n `agent-tool pr preflight <reviewed-head> <base-branch> <reviewed-base>` to\n recheck CI, conflicts, the live base, PR identity, local state, and explicit\n version policy. When versions are managed,\n `agent-tool versions check <live-base-oid>` must pass. Use the squash-merge\n skill to merge the exact reviewed HEAD.\n6. After confirmed MERGED, follow the reset skill: run\n `agent-tool repo cleanup <PR-number> <reviewed-head> --apply` to return to the\n updated default branch and prune the shipped feature branch, honoring\n stronger repository cleanup rules. Never prune with raw `git branch -D` or\n `git push --delete`: the cleanup command checks the merge and both refs\n first, and harness command guards prompt for raw force deletes. If the user requested keep-branch, preserve\n both feature refs. Check the cleanup receipt and verify the local feature ref\n is absent unless preserved; report incomplete cleanup explicitly. Apply\n documented dependency/hook setup.\n7. When the project publishes npm packages, use `agent-tool release verify\n <package> <version> <merge-oid> --workflow <publish-workflow>` to verify the\n exact workflow and tarball, allowing registry propagation time. When the\n project deploys the merged branch, verify that deployment and documented\n live checks. Report deployment failures\n separately from a successful merge; follow project policy for repairs. A\n release that fails because another merge published the same version needs\n a follow-up version bump through this workflow.\n8. Run `agent-tool repo base-health` again until it is no longer `pending` and\n the merge commit, or a newer tip, has runs (`tip.hasRuns`). When no run\n starts within about ten minutes, as with path filters or PR-only CI, or the\n status is `no-ci`, report that and stop waiting. A failure there belongs to\n this session: fix it forward through this workflow before reporting the\n work done.\n\nBefore the final report, run `agent-tool teardown` in each repository this work\ntouched. Stop what the work started (`teardown --apply`, `proc stop`), stop any\nuntracked process it started, and remove worktrees it added. Report what\nremains and why; the work is not done while teardown fails for anything it\nstarted.\n\nNever infer a clean review from process success alone, or carry a review to a\nHEAD that `review carry` does not accept. Do not weaken configured CI policy to\nget a merge through. If a step fails, preserve useful intermediate work and report the concrete\nremaining issue. Report PR link, merged commit, review verdict, validation, final\ncheckout state, the base's health at the start and end and anything repaired or\nhardened, the teardown result, and whether the shipped local branch was pruned\nor preserved.\n",
|
|
13
14
|
"space-cleanup": "---\nname: space-cleanup\ndescription: Free disk space safely in a repository, across a matrix workspace and its checkouts, or in this machine's developer caches, by removing only regenerable, git-ignored output after a dry run. Use when the disk is low, `bun run health` asks for space, a command fails with ENOSPC, or the user asks to clean up space; not for deleting clones, branches, or anyone's work.\n---\n\n# Space Cleanup\n\nFree space by removing what a command can rebuild, never what a person made.\nMeasure first, remove the cheapest tier that frees enough, and report what\nwas freed from the volume's real free space, not from the estimate.\n\n## Run it\n\n`agent-tool space` does the work; run the repository's pinned agent-tool\n(`bun run agent-tool space` or `node_modules/.bin/agent-tool space`). It is a\ndry run until `--apply`.\n\n- In a repository: `agent-tool space [path...] [flags]`. With no paths it\n covers only the repository holding the working directory; each path names\n the repository holding it.\n- From a matrix workspace (`matrix.json` beside `checkouts/`):\n `agent-tool space [checkout...] [flags]`. With no names it covers the\n workspace and every checkout in `checkouts/`; names are checkout names or\n `owner/name`.\n- If the pinned agent-tool predates the command, run\n `bunx --bun @a2f0/agent-tool@latest space`.\n\nCaches are always included; each other flag adds its own tier independently:\n\n| Flag | Removes | Cost to restore |\n| --- | --- | --- |\n| (default) | Caches: `.turbo`, `.parcel-cache`, `.eslintcache`, `.stylelintcache`, `coverage`, `.nyc_output`, test reports (`test-results`, `playwright-report`, `blob-report`), Python caches (`__pycache__`, `.pytest_cache`, `.mypy_cache`, `.ruff_cache`), `node_modules/.cache` and `.vite`, `.next/cache`, `.wrangler/tmp` | Next run is slower |\n| `--builds` | Build output: `dist`, `build`, `out`, `.next`, `.nuxt`, `.output`, `.svelte-kit`, `.expo`, `.gradle`, `.build`, `DerivedData`, Rust `target`, `*.tsbuildinfo` | The repository's build |\n| `--deps` | `node_modules`, `.venv`, CocoaPods `Pods`, `vendor/bundle` | The repository's documented install |\n| `--machine` | Xcode DerivedData (not its `SourcePackages` clones), `brew cleanup`, Bun and npm caches, `pnpm store prune` | Re-downloads and rebuilds |\n\n`--json` gives agents the same report, and the command exits 1 when a\nrepository could not be scanned or a removal failed, 2 when it cannot run at\nall (an unknown option, or processes that cannot be listed).\n`--include-busy` cleans repositories other processes are working in; use it\nonly after confirming those processes are your own or finished. It never\napplies to `--machine` items, which always wait for running installs and Xcode\nbuilds.\n\n## Procedure\n\n1. Check the volume: `df -h .` (on macOS, `df -h /System/Volumes/Data`). Note\n how much the task needs; matrix sweeps want 50 GiB free.\n2. Run the dry run with `--builds --deps --machine` to see every tier's size,\n then choose the cheapest set of tiers that frees enough. Default caches\n alone are always fine to apply.\n3. Apply with only the chosen flags plus `--apply`. Read the `Free: before ->\n after` line; APFS clones and hard links mean freed space can be far less\n than the listed sizes, and Time Machine local snapshots can hold it until\n macOS thins them.\n4. After `--deps`, reinstall dependencies in each cleaned repository that will\n be used next, with its documented setup, so hooks and `status` keep\n working. Deleting `node_modules` also deletes the pinned agent-tool, so\n where setup runs `bun run agent-tool bun install`, first bootstrap with the\n repository's pinned Bun: `bun install --frozen-lockfile`.\n After `--builds`, nothing is needed: the next build regenerates output.\n5. Report the before and after free space, the tiers applied, repositories\n skipped as busy, and the `review` items from `--machine` with their sizes,\n so the user can decide about them.\n\n## Safety rules\n\nThe command enforces these; keep them when cleaning by hand:\n\n- Remove a repository path only when git reports it ignored, nothing under it\n is tracked (rechecked just before removal), its name is on the tier's list,\n nothing under it is a repository, `.env` file, `.secrets`, or SQLite\n database, and neither it nor any parent inside the repository is a symlink. Untracked files that are not ignored\n belong to someone: never remove them.\n- Never run `git clean` (`-X` included), `rm -rf` on a whole ignored tree, or\n delete `.env*`, `.secrets`, `.wrangler/state`, local databases, or anything\n under `../matrix-secrets`.\n- Skip a repository another process is working in (a dev server, a test run,\n another agent session). Idle shells and the session running the command do\n not count. When processes cannot be listed, the command stops instead of\n guessing.\n- Never delete clones, worktrees, branches, stashes, Docker data, Gradle\n caches, simulator devices (unavailable ones included: they keep app data),\n or iOS DeviceSupport on your own: the `--machine`\n report lists the large ones as `review` for the user to decide.\n- Package caches wait while an install runs, and DerivedData waits for Xcode.\n- In a matrix workspace, cleaning ignored output does not change any\n checkout's git state, so it is not a sweep and needs no ledger; a checkout's\n `status` need not be `ready`.\n\n## Ownership\n\nagent-tool (`a2f0/agent-tool`) owns this skill at `skills/space-cleanup/` and\nthe command at `src/space/`, 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",
|
|
14
15
|
"squash-merge": "---\nname: squash-merge\ndescription: Squash-merge a reviewed GitHub pull request while binding the mutation to the reviewed commit and checking CI.\n---\n\n# Squash Merge\n\nUse the installed `agent-tool` and repository merge policy. Merge only within\nthe user's authorized scope. Have the exact reviewed HEAD, base commit, and base\nbranch available, and read the verdict and unresolved findings. BLOCKER or MAJOR\nfindings require repair and a new review before merging.\nFollow the repository's review-bot policy and require all actionable blocking\nreview feedback to be addressed before merging.\n\nWait with `agent-tool pr checks --wait --head <reviewed-head>`, which waits for\nchecks to appear and for every workflow/job/event entry to finish, and reports\n`behind: true` when the live base has moved past the head. A moved base alone\nneeds no integration: integrate, validate, review, and push again only when\nGitHub reports a conflict, when `versions check` fails against the live base,\nor when the repository sets `merge.requireStrictBaseFreshness`. Under that\npolicy the wait stops early at `behind: true`; cancel that head's runs with\n`agent-tool pr cancel-runs --head <reviewed-head>` first. Run\n`agent-tool pr preflight <reviewed-head> <base-branch> <reviewed-base>` immediately\nbefore merging. It checks local and PR identity, that the head contains the\nreviewed base, conflicts and merge readiness, explicit version policy against\nthe live base, configured strict rulesets, and passing checks; under the strict\npolicy the live base must also equal the reviewed one. If an identity changed,\nrefresh, integrate, validate, and review again; a new HEAD that\n`agent-tool review carry <reviewed-head> <new-head>` accepts keeps the earlier\nclean review. Read unresolved feedback with `pr threads list` and follow\nproject review policy.\n\nUse a title that satisfies `agent-tool.json` and pass both reviewed HEAD and\nbase branch:\n\n```sh\nagent-tool pr merge 'feat: describe the change' <reviewed-head-oid> <base-branch>\n```\n\nThe helper enforces HEAD atomically through GitHub's `expectedHeadOid`, checks\nCI, rejects queued or automatic merges, and creates a subject-only squash with\nthe PR reference. GitHub has no atomic expected-base argument in this mutation,\nso a base can move between preflight and merge; without the strict policy that\nis accepted, and a break the combination causes is repaired on the base. With\n`merge.requireStrictBaseFreshness`, the helper refuses to merge unless an\nactive strict status ruleset that the actor cannot bypass protects the base. Do\nnot retarget the PR concurrently with merging.\n\nConfirm GitHub reports MERGED before any cleanup. A failed or uncertain mutation\nis not evidence of a merge. Preserve the branch on failure. After a confirmed\nmerge, perform checkout cleanup only when requested or as part of an authorized\nshipping workflow, with `agent-tool repo cleanup <PR-number> <reviewed-head>\n--apply` rather than raw `git branch -D`. Report the PR and merge result.\n",
|
|
16
|
+
"take-screenshots": "---\nname: take-screenshots\ndescription: Capture a repository's app screenshots once into the shared matrix-artifacts store, so every clone builds and deploys the newest captures, and check a capture's provenance before a deploy. Use when asked to take, refresh, or check screenshots, before deploying a site or store listing that shows them, or when adding screenshot capture to a repository.\n---\n\n# Take Screenshots\n\nScreenshots are captured once, in any clone, into the shared store's\n`matrix-artifacts/<project>/screenshots`, beside the matrix workspace (or\nbeside the clone outside one). Every clone of the repository links its\ngitignored `.screenshots` there, so a website deploy or\nstore upload in another clone publishes the same, newest captures without\nrecapturing. Brand images are not part of this: they render from\n`assets/brand/*.svg` in each clone.\n\n## Run it\n\n`agent-tool screenshots status|link|capture` does the work; run the\nrepository's pinned agent-tool (`bun run agent-tool screenshots ...` or\n`node_modules/.bin/agent-tool screenshots ...`). `link` and `capture` are dry\nruns until `--apply`; `--json` gives agents the report.\n\n- From any clone: `agent-tool screenshots <command>` covers that repository.\n- From a matrix workspace: `agent-tool screenshots <command> [checkout...]`;\n with no names it covers every checkout that captures.\n- If the pinned agent-tool predates these commands, run\n `bunx --bun @a2f0/agent-tool@latest screenshots <command>`.\n\n| Command | Does |\n| --- | --- |\n| `status [repo...] [--all]` | Link state of each clone and its newest capture relative to HEAD |\n| `link [repo...] [--all] [--apply] [--supersede]` | Point `.screenshots` at the store; moves an existing capture into an empty store, or with `--supersede` to `<project>/superseded/` |\n| `capture [repo] [--apply] [--allow-dirty] [-- args...]` | Once its checks pass, link every clone of the store's projects that has no `.screenshots`, then run the repository's `screenshots` package script under the project lock and record `capture.json` |\n\n`--all` selects every clone on this machine whose project the store already\nholds, beside the store or in a matrix workspace's checkouts, worktrees\nincluded: `link --all --apply` links them all in one run.\n\n`MATRIX_ARTIFACTS_DIR` overrides the store location, and `--project <name>`\nnames the namespace of a repository without a GitHub origin. `status` exits 1\nwhile a selected clone is not linked, `link` while one is blocked, and an\napplied `capture` when it did not finish `complete`; each exits 2 when it\ncannot run at all.\n\n## Procedure\n\n1. `status` first. If the clone is not `linked`, run `link`, then\n `link --apply`; `capture` links a clone with no `.screenshots` itself, and\n `status --all` or `link --all` covers every clone on this machine. A\n `blocked` result names what a person must decide (two\n different captures: compare their dates and commits, and if the store's is\n newer rerun with `--supersede`, a link that points elsewhere, a `.screenshots/` ignore\n pattern that needs its trailing slash removed in a PR).\n2. Decide whether to capture. If the newest capture is `complete`, `merged`,\n and no screens changed since its commit, reuse it: that is the point of the\n store. Recapture after UI, seed data, or capture-code changes, after a\n `failed` capture, or when asked.\n3. Commit first: capture refuses a dirty tree, because the shared store would\n publish uncommitted work. `--allow-dirty` is for a local-only look: it marks the\n capture `dirty`, which builds refuse, so recapture from a commit before\n anyone deploys.\n4. Read the repository's capture docs for prerequisites (simulators, Maestro,\n Playwright browsers, seed data, mise-pinned tools). Maestro drives one\n device at a time on this machine: check for a running `maestro` first.\n5. Run `capture` as a dry run, then with `--apply` through output capture\n (`agent-tool run --label screenshots -- agent-tool screenshots capture\n --apply`, with the repository's pinned agent-tool for both). Captures take\n minutes; run them in the background and do not start a second one for the\n same project (the lock refuses it).\n6. Verify the result, not just the exit code: `status` shows `complete` at your\n commit, and spot-check a few images (open them; check light and dark, each\n layout, and the expected dimensions).\n7. Report the capture's commit, whether it was partial (`args`), and which\n clones see it. Before a deploy, quote `status` for the deploying clone.\n\n## Rules\n\n- Never run a repository's `screenshots` package script directly for a shared\n capture; the lock and `capture.json` keep clones from publishing a partial\n or concurrent capture.\n- Never commit screenshots, copy them into a repository, or delete the store.\n Never remove `.screenshots` itself; capture code clears files inside it.\n- Builds and deploys never capture. `agent-tool screenshots build`, which\n stages screenshots into a website, reads `.screenshots/capture.json` before\n and after copying, and refuses `running`, `failed`, `incomplete`, or `dirty`\n captures and a record that changed meanwhile.\n- Before a deploy that publishes screenshots, run `status` and report the\n capture's commit; recapture only when the screens it shows changed since.\n\n## Adding capture to a repository\n\nFollow `references/adding-capture.md`: the package script, ignore pattern, and\noutput layout every repository shares, and the Playwright (web) and Maestro\n(native) patterns tearleads and nc use. In a matrix workspace, its audit checks\nit with `bun run audit --rule screenshots-store`.\n\n## Ownership\n\nagent-tool (`a2f0/agent-tool`) owns this skill at `skills/take-screenshots/`\nand the commands at `src/screenshots/store/`, with their tests beside them;\n`agent-tool skills install --apply` installs it in each adopting repository.\nThe store's layout and record are described in its `docs/screenshots.md`.\nChange them there, never in an installed copy.\n",
|
|
15
17
|
"update-dependencies": "---\nname: update-dependencies\ndescription: Update dependencies or update everything in a repository, including runtimes, tools, and CI pins, with compatibility checks and safe previews; ship through review, CI, merge, and release verification unless a narrower scope is requested.\n---\n\n# Update Dependencies\n\nUse the repository's package managers and installed `agent-tool`. Read `AGENTS.md`,\nREADME, existing dependency-maintenance notes, linked setup/release documents,\nand repository-owned upgrade skills before editing. Follow their hooks, version\npolicy, checks, and requested stopping point.\nUpdate applicable dependencies throughout the repository, including workspaces\nand examples. When asked to perform dependency updates, invoke the installed\n[`ship-pr`](../ship-pr/SKILL.md) to complete review, PR, CI, and merge, then verify\nthe repository's normal merge-triggered publication or deployment. An explicit\nnarrower scope, such as inventory-only, local changes, or open-PR-only, takes\nprecedence. This default does not authorize standalone infrastructure applies,\ndeployments, or global tool changes. Default dependency-update merge subject:\n`chore: update dependencies`, subject to repository title policy and any explicit\nuser subject.\n\nRun noisy installs, checks, tests, and builds with\n`agent-tool run --label <check> -- <command> [args...]` to retain full private\nlogs and return the original status with compact output. Inspect bounded excerpts\nusing `agent-tool logs <log>` and targeted searches for warnings and evidence;\na successful receipt does not establish a warning-free upgrade. Keep structured\naudit/plan results, deployment previews, and review findings directly visible\nwhen they drive a safety decision. Do not dump full suite logs into context,\nsilence warnings at their source, or change check scope to reduce output.\n\n## Checkout setup\n\nThis shared workflow also handles natural-language requests to \"update everything\".\nIf the repository owns an `update-everything` wrapper, read and follow its extra\nrequirements; do not create an alias or overwrite that skill. The workflow works\nfrom a standalone checkout with no workspace coordinator.\n\nAfter a fetch, branch integration, or dependency pin change, check that the local\n`agent-tool --version` matches the repository's declared pin before trusting its\ncommands or generated skills. A stale CLI can reject newer configuration keys.\nAfter screening install scripts and hooks as below, run the documented frozen\ninstall with the repository's pinned runtime. For Bun projects, an already working\nCLI can run `agent-tool bun install`; if it is missing or cannot parse the new\nconfig, run the documented package-manager install directly. A known working\nexecutable may capture it with `agent-tool --repo <checkout> run --label setup --\n<install-command> [args...]`. Do not fetch an unpinned CLI, alter global tools, or\nassume a sibling workspace exists. Verify the installed version afterward; if it\nstill differs, report the mismatch rather than deleting arbitrary dependencies.\n\nAfter upgrading agent-tool, run the repository's skill/permission sync commands.\nFor each ownership manifest they do not refresh, run its installer directly:\n`agent-tool skills install --harness <existing-scope> --apply` for\n`.agent-tool-skills.json`, and\n`agent-tool permissions install --harness <existing-scope> --apply` for\n`.agent-tool-permissions.json`. Preserve each harness scope, and commit the\nownership manifests with any generated files.\nThe manifests record the agent-tool version, so every upgrade changes them, even\nwhen no skill or rule changed, and `skills check` and `permissions check` fail\nuntil the sync records the new version. Hermes reads the shared `.agents/skills`\nin a trusted project; the installer does not grant trust. If discovery is\nunavailable, read those files directly rather than silently using a stale global\ncopy.\n\n## Nonblocking execution\n\nUse the harness's managed background execution for long finite checks, reviews,\npush hooks, CI waits, and release verification; request completion notification\nwhen available and retain its process handle plus agent-tool's log/receipt path.\nRun `run-group` and reviews directly so their reports remain visible. A started\nprocess is not a passed check: read its final status and required evidence before\nshipping, and do not repeatedly poll when completion events are available.\nWithout harness background support, `proc start --label <name> -- agent-tool run\n--label <check> -- <command> [args...]` records the outer process and captures\nits output; inspect `proc list` and `logs` plus the inner run receipt to establish\ncompletion and exit status. An exited process record alone does not prove success.\nUse `proc stop`/`teardown` for owned leftovers; never stop another session's work.\nThese commands need no matrix workspace or global configuration change.\n\nKeep independent compatibility groups moving while a producer release or an\nexternal gate is pending. Only final adoption of that exact published release\nmust wait. Bound CPU/process-heavy concurrency to the machine's available budget;\na failed full suite needs diagnosis and a full-scope rerun, not larger timeouts,\nfewer assertions, or a focused retry presented as suite recovery. Background\nexecution never bypasses an approval, a deployment preview, or exact-head review.\n\n## Safety before execution\n\n**Always dry-run before any infrastructure apply or deployment. Never destroy,\nreplace, or recreate a resource during an upgrade.** This includes Terraform,\nOpenTofu, Wrangler, Ansible, other infrastructure tools, and effects triggered by\ninstallation, tests, hooks, Git push, opening a PR, CI, or merging. Greenfield\nprojects and approval to ship do not waive this rule.\n\nBefore running project commands or pushing, trace their scripts, hooks, workflow\ntriggers, reusable workflows, and deployment commands. A dry-run flag alone is\ninsufficient: inspect tasks, provisioners, plugins, external programs, and actions\nthat can mutate despite preview mode. Avoid such a preview unless its effects\nare proven read-only. Do not run destroy/delete, taint/replace, state removal,\nbackend migration, forced database reset, or an automatic \"repair\" that bypasses\nthe rule. Do not hide destruction with targeting, disabled refresh, ignored\nchanges, new resource identities, or weakened policy.\n\nPreview with the proposed versions and complete configuration for each affected\nenvironment, using its real backend/workspace/account, variables, inventory, and\nresource identities. An empty local state, mocked credentials, validate-only run,\nor bundle build cannot establish safety for production. Check the current baseline\nas well when needed to distinguish existing drift from the upgrade. Keep state,\nbinary plans, JSON plans, and secret-bearing diffs out of Git and public reports.\n\nIf a preview proposes deletion or replacement, fails, is incomplete, omits\naffected resources, or cannot establish safety, skip that dependency and its\ncoupled migrations. Restore only this task's edits to the affected compatibility\ngroup, retain independent safe upgrades, and record the reason and affected\nresources. Never apply to find out. A preview is not deployment authorization.\n\nBefore an authorized apply/deploy, verify the exact validated commit, toolchain,\nconfiguration, environment, and current state still match the preview. Re-preview\nafter relevant changes or drift. CI must enforce the same order and stop on an\nunsafe preview before mutation; a successful local preview does not excuse an\nunguarded push- or merge-triggered deployment. Establish a narrowly scoped guard\nwhen authorized and reviewable, or hold the affected upgrade before triggering\nthat workflow. Do not disable protections to ship. A plan must be inspected before\nthe operation; inspecting deployment logs afterward is too late.\nAn unsafe workflow triggered on every branch push also blocks pushing otherwise\nindependent upgrades until that trigger has a proven safe guard.\n\n### Terraform and OpenTofu\n\nRead core, provider, and module upgrade guides, including intermediate major\nmigrations. Regenerate provider locks with the pinned CLI, preserving supported\nplatform hashes. Backend initialization/migration is also subject to the safety\ngate. Inspect external data programs and provisioners before planning.\n\nUse a full refreshed saved plan with locking and the real variables, for example\n`terraform plan -input=false -out=<private-plan>`; if using `-detailed-exitcode`,\n0 and 2 are success, 1 is failure. Inspect `terraform show -json <private-plan>`.\nRun `agent-tool dependencies check-terraform-plan <private-plan.json>` to check\nsupported JSON resource actions. It fails for every action containing `delete`,\nincluding both replacement orders, unknown actions, incomplete/deferred plans,\nfailed checks, or opaque provider action invocations. It prints actions and\ndiagnostics without resource attribute values; it does not prove that a plan is\nfresh, comprehensive, authentic, or that provider code has no hidden effects.\nOlder/unsupported plan formats that cannot establish completeness are skipped.\nOpenTofu currently omits `complete` in its JSON format and is rejected by this\nhelper; report that limitation rather than adding a synthetic completeness flag.\nAlso inspect resource identity, drift, warnings, provider semantics, and any\neffects outside resource actions. For an authorized apply, consume the exact\napproved saved plan, not an uninspected newly generated plan.\n\nSource: [Terraform JSON plan format](https://developer.hashicorp.com/terraform/internals/json-format).\n\n### Wrangler and other deployment tools\n\nUse the proposed pinned Wrangler for `wrangler deploy --dry-run` with the same\nbuild/configuration/environment used by deployment. This checks bundling, not a\ncomplete remote resource plan. Separately verify account, worker name, routes,\nbindings and resource IDs against the existing deployment and read migration\nsemantics. Review Durable Object deleted/renamed classes, D1 schema/data\nmigrations, storage resources, queues, containers, and deployment integrations.\nNever infer \"no destruction\" from a successful bundle. Resource removals,\nreplacement, or unprovable remote effects skip the affected group. Apply the\nequivalent preview and identity checks to other tools rather than assuming they\nshare Terraform's guarantees.\n\nDo not assume `wrangler d1 migrations list --remote` is read-only. The\nimplementation inspected for this skill initializes migration tracking with\n`CREATE TABLE IF NOT EXISTS`; verify the pinned Wrangler version before using\nthe command. Verify database identity and compare migration files with the\ndatabase's configured migration tracking table through audited read-only\nqueries. A missing table, pending migration, or unverifiable schema/data\neffects hold the affected upgrade/deployment group. Never initialize schema\nmerely to establish preview safety.\n\nWrangler runs a custom `build.command` again during deployment. Use supported\nconfiguration referencing the same validated artifacts for both preview and\ndeployment, preventing another unvalidated build before upload. Bind the\nartifacts, configuration, and pinned tool to the authorized commit, and recheck\ntheir identities before upload and after relevant changes. Hold the affected\ngroup if the pinned Wrangler cannot upload the validated output without\nrebuilding it, or if the upload cannot be proven to match the preview.\n\nSources: [Wrangler command documentation](https://developers.cloudflare.com/workers/wrangler/commands/),\n[D1 migration listing implementation](https://github.com/cloudflare/workers-sdk/blob/e3d186776fcc2e4b5cc4cfd7155591778a375957/packages/wrangler/src/d1/migrations/list.ts),\n[migration table initialization](https://github.com/cloudflare/workers-sdk/blob/e3d186776fcc2e4b5cc4cfd7155591778a375957/packages/wrangler/src/d1/migrations/helpers.ts),\nand [Wrangler custom builds](https://developers.cloudflare.com/workers/wrangler/custom-builds/).\n\n### Ansible\n\nCheck controller Python, ansible-core, collections/roles, and target Python support\ntogether; read porting guides. Inspect all tasks and invoked scripts before\n`ansible-playbook --check --diff` with the real inventory and variables.\n`check_mode: false` forces mutation even with `--check`; unsupported modules and\nconditions based on registered results can omit effects. Inspect deletion,\nrecreation, service/data reset, and package removal semantics beyond the diff.\nSkipped or opaque tasks are a safety gap, not a clean preview. Redact diffs.\n\nSource: [Ansible check mode limits](https://docs.ansible.com/projects/ansible/latest/playbook_guide/playbooks_checkmode.html).\n\n## Inventory and choose compatible targets\n\nRecord each dependency source, current resolved version, latest stable candidate,\nselected target, compatibility constraints, upstream migration links, and checks\nin the run ledger described under Report.\nQuery authoritative registries, official releases, support matrices, and migration\nguides at execution time; do not treat remembered versions or prereleases as\nlatest stable. Inspect runtime requirements, peer dependencies, ABI/API changes,\nplatform availability, maintained release lines, and changed defaults, including\nsecurity, privacy/telemetry, data retention, and postinstall/native behavior.\nCheck transitive dependencies' peer/runtime constraints as well as direct ones. Unsupported\nor unpublished targets stay pinned with an explanation.\n\nInventory manifests, locks, tool configuration, CI/reusable actions, containers,\nscripts, deployment files, and executable documentation. Search duplicate version\npins and aliases, not just filenames; exclude vendored/generated snapshots unless\nthe repository owns their update process. Examples of sources to inspect:\n\n| Ecosystem | Sources and compatibility group |\n| --- | --- |\n| JavaScript/TypeScript | All package.json dependency fields, overrides/resolutions, workspace catalogs, packageManager/engines, npm/Bun/pnpm/Yarn locks, Node/Bun pins, compiler and lint/build/test plugins |\n| Toolchains | mise.toml/.mise.toml, mise.lock, .tool-versions, runtime version files, tool URLs/checksums, CI pins and container images; include every tool declared by mise, not just mise itself |\n| Python/Ansible | pyproject/requirements, uv/Poetry/pip locks, Python pins, ansible-core, collection/role requirements, lint plugins and managed host constraints |\n| Ruby/iOS | .ruby-version, Gemfile/lock, Bundler, CocoaPods, Podfile/lock, podspecs, Swift packages and Xcode/iOS deployment requirements |\n| Infrastructure | Terraform/OpenTofu CLI constraints, provider locks/constraints, module versions/Git refs, Wrangler and Cloudflare integration dependencies |\n| CI/system/native | Actions/reusable workflow refs, Docker tags/digests, OS images/packages, Rust/Cargo toolchain and locks, Go modules, Gradle/AGP/Kotlin/JDK and other repository-specific manifests |\n\nBuild connected compatibility groups before editing. Select the newest supported\ncombination, which can be older than an individual package's latest. Upgrade the\nframework first or keep its compatible toolchain pinned; do not force peer\nresolution, drop compatibility checks, or add blanket overrides to make installs\npass. Preserve source pin policy (exact version, digest, full Git SHA) and resolve\nimmutable pins from verified upstream releases. Preserve intentional runtime\nminimums unless migration requires changing the support contract.\n\nFor React Native, use its version-specific upgrade guide/template diffs and\nrepository upgrade skills. Couple React and its renderer, native modules,\nMetro/Babel, CLI, codegen, Hermes/New Architecture, CocoaPods/Bundler/Ruby,\nXcode/iOS deployment targets, and Android Gradle/AGP/Kotlin/JDK/SDK/NDK. For Expo,\nuse the chosen SDK's supported React Native/dependency matrix and its dependency\nchecks. Do not independently update framework-managed pods or generated native\nfiles; use the framework's regeneration workflow and prove iOS/Android builds.\nPermissive peer ranges alone do not prove native renderer or toolchain compatibility;\ncheck the framework's actual supported versions and native implementation.\nAn unavailable native toolchain is a reported validation limit; do not claim the\ngroup verified. See [React Native upgrading](https://reactnative.dev/docs/upgrading).\n\nCheck developer tools' own dependencies too: a compiler release without its old\nprogrammatic API may break test/lint runners that import it even when `tsc` passes.\nAction runtime upgrades can require newer self-hosted runners; preserve workflow\npermissions, action inputs/outputs, caching, artifact semantics, and job names.\n\nCheck current advisories with read-only ecosystem audits against the baseline and\nproposed lockfiles, using the repository's configured registry/advisory sources.\nDo not send private dependency metadata to an unconfigured or unauthorized service;\nreport the resulting coverage limit. Cover direct and resolved transitive dependencies,\nincluding native/platform-specific binaries. Latest direct packages can still\npin vulnerable transitive versions. Trace each finding to its owning dependency,\nverify affected versions, runtime conditions, and remediation in the maintainer's\nadvisory and fixed release. When the owner's range permits a fixed version, use a\ntargeted refresh with the lockfile's owning manager and preserve unrelated\nresolutions; otherwise prefer a supported owner upgrade.\nIf the owner still pins a vulnerable version, a narrowly scoped security patch\noverride may be used only with API/ABI/runtime compatibility evidence and focused\nregression checks of the actual affected integration. Document its rationale and\nremoval condition; a passing install or bundle alone is insufficient. Do not run\nblind audit fixes or use blanket overrides to bypass compatibility constraints.\nReport unresolved advisories and unavailable audit coverage accurately; current\ndirect pins or a partial clean audit do not\nestablish that the whole dependency graph is safe.\n\n## Migrate and validate\n\nCapture relevant baseline checks and warnings first, after screening their side\neffects. Update one compatibility group at a time. Read the upstream instructions\nfor every breaking step; implement required source/config/schema migrations and\nremoved API replacements. Use the manager that owns each lockfile, on the selected\nruntime, and inspect the resulting diff. For Bun lockfiles, change declared\nversions with `agent-tool bun update <name[@version]>` and drop packages with\n`agent-tool bun remove <name>`; both use the pinned Bun and refuse to add a\npackage. A new dependency goes through `agent-tool bun add <name@version>`, which\nasks for approval; never introduce one by editing `package.json` and\nreinstalling. For existing Bun catalog entries use\n`agent-tool bun update --catalog default <name@version>...` (or the existing named\ncatalog). Name an explicit exact/ranged registry spec; keep `catalog:` references,\nworkspace membership, other entries, and peer compatibility contracts intact.\nThe helper refuses intake and ambiguous layouts and uses the owning manager to\nrefresh the lock; do not replace catalog references with direct versions.\n\nFor an already-resolved transitive registry package with an eligible owner range,\nuse `agent-tool bun update --resolved <name>...` with the owning Bun 1.4.4 or newer.\nIt selects every locked copy of those names, never a requested version or glob,\nand accepts only a result with identical manifests and unchanged non-target lock\nentries/metadata. It preserves release-age, overrides and patches. If an older\nmanager is pinned, or a required new child prevents a target-only result, this\npath is unsupported: prefer an owning-dependency upgrade through the normal\nhelper, or obtain approval for an explicitly reviewed manager workflow. Do not\nsilently substitute a broad refresh or add a transitive package directly. Inspect\nthe receipt/logs and re-audit; a no-op or warning can leave an advisory unresolved.\nNever hand-edit integrity hashes or lock entries.\nReview intentional patches, overrides, and pins before removal; retain them until\nupstream fixes and regression checks demonstrate they are unnecessary.\nAvoid unrelated global installations or environment changes. Use task-local or\nrepository-scoped tools for testing changed runtime pins.\nFor published packages, also validate tarballs and consumer installs with their\ndocumented supported package managers, including manifest/override syntax and\nruntime requirements. A successful owning-manager install does not prove that\npublished metadata works for those consumers.\n\nRun the repository's setup/hooks, frozen installs, lint, typechecks, tests, builds,\npackage/platform smoke checks, and relevant safe integration previews. Resolve\nupgrade-related deprecation warnings at their source. Do not suppress warnings,\nweaken tests, or disable checks; report remaining upstream/pre-existing warnings\nwith evidence and keep a target pinned when migration cannot be completed.\nAdd focused regression coverage when a migration changes behavior; avoid tests\nthat merely assert version strings. Re-run checks after repairs. Report checks\nblocked by missing credentials, platforms, or external services accurately.\nRe-audit the final resolved graph after migrations and repairs.\n\nConfirm every inventory row is upgraded, already current, intentionally constrained,\nor skipped with a concrete reason. Do not present an unresolved group as complete.\nWhen upgrading agent-tool itself, install its managed skills with the same harness\nscope and commit the ownership manifest; never edit generated managed skill copies.\n\nWhen changes depend on another repository's release, ship the producer first and\nconfirm publishing and registry availability before pinning the consumer; include\nits exact version/commit and API migration notes. Independent groups may proceed.\nComplete the installed `ship-pr` workflow within the requested scope, including\nindependent review of every changed HEAD, required CI and review feedback, merge,\nand verification of the merge's normal publication or deployment. Do not stop at\nan open PR unless the user requested that stopping point or a concrete blocker\nprevents continuing. Check deployment safety again before push/open/merge;\nshipping defaults do not waive the preview gates above.\n\n## Report\n\nKeep run-specific evidence in the upgrade PR body or a linked PR comment: the\ninventory and old/selected versions, completed migrations, validation and warnings,\nbaseline/final audits and coverage limits, preview environment/commit/tool versions\nand safe action summary, and skipped/constrained dependencies with reasons. Include\nsecurity overrides, their rationale and removal condition, and unresolved advisories.\nIf the user requested a scope that stops before a PR, provide this ledger in the\ntask report and honor that limit. For a sweep, keep one entry per repository,\nincluding unready and unchanged checkouts, and use an existing tracking issue only\nwhen explicitly requested. Never create an issue merely to store upgrade evidence.\n\nKeep durable repository guidance focused on what the next upgrade needs: current\ncompatibility constraints, intentional pins/overrides, unresolved advisories, and\nreusable repository-specific procedures. Prefer the existing maintenance document;\notherwise create `docs/dependency-upgrades.md` (or the repository's equivalent)\nonly when there is substantive guidance to preserve. For each constraint, record\nits rationale, upstream advisory/migration/issue link or originating PR, and the\ncondition and check for removing or revisiting it. Do not copy version inventories,\naudit output, validation/preview receipts, or dated run journals into that document.\n\nOn every upgrade, reconcile the existing maintenance document against the final\ndependency graph and checks: update constraints in place, remove resolved entries,\nand link the PR for historical evidence. Keep the root README focused on purpose,\nsetup, supported requirements, and normal usage, with a concise maintenance link\nwhen needed. Keep dependency-maintenance guidance in `AGENTS.md` to a short\nrouting rule and link; do not accumulate upgrade reports in either entrypoint\nor duplicate the maintenance document.\n\nFor shipping, report the branch, reviewed commit/verdict, PR, merge, publish/deploy\nresult, and final checkout state. Keep full logs private; never publish credentials,\nstate, or plan contents in any of these locations.\n"
|
|
16
18
|
};
|
|
17
19
|
/** Files a skill ships beside its SKILL.md (Markdown references, then Codex's agents/openai.yaml), by skill and then by path within the skill directory. */
|
|
@@ -31,6 +33,10 @@ export const BUNDLED_SKILL_REFERENCES: Readonly<Record<string, Readonly<Record<s
|
|
|
31
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",
|
|
32
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"
|
|
33
35
|
},
|
|
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",
|
|
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
|
+
},
|
|
34
40
|
"performance-pass": {
|
|
35
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",
|
|
36
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"
|
|
@@ -43,5 +49,9 @@ export const BUNDLED_SKILL_REFERENCES: Readonly<Record<string, Readonly<Record<s
|
|
|
43
49
|
},
|
|
44
50
|
"space-cleanup": {
|
|
45
51
|
"agents/openai.yaml": "interface:\n display_name: \"Space Cleanup\"\n short_description: \"Free disk space by removing regenerable output safely\"\n default_prompt: \"Use $space-cleanup to free disk space here: dry run first, then remove only the tiers needed.\"\n"
|
|
52
|
+
},
|
|
53
|
+
"take-screenshots": {
|
|
54
|
+
"references/adding-capture.md": "# Adding screenshot capture to a repository\n\nEvery repository that captures screenshots follows one contract, so\n`agent-tool screenshots capture`, the shared store, and the matrix audit work\nthe same way everywhere. The capture code itself stays in the repository: it knows the\napp's routes, seed data, and devices.\n\n## Contract\n\n- Root package script `screenshots` runs the whole capture and forwards extra\n arguments (a layout or project filter) to the runner.\n- It writes below `<root>/.screenshots/`, resolved from the repository root,\n never from the current directory. Honor `SCREENSHOT_OUTPUT_DIR` when the\n runner already supports it, defaulting to `.screenshots`.\n- The root `.gitignore` lists `.screenshots` with no trailing slash, so the\n symlink to the store is ignored too.\n- Capture code removes or replaces files inside `.screenshots`, never\n `.screenshots` itself, and leaves `capture.json` alone.\n- Builds never capture. A `build:*` or deploy script reads `.screenshots`\n only. A build that publishes screenshots checks `.screenshots/capture.json`\n before and after copying and prints the capture's commit (see\n [deploy guard and gallery](#deploy-guard-and-gallery)).\n- Browser phone layouts are captured at the full 390x844 screen, so framed\n phones keep a real phone's proportions; native store captures keep each\n device's required size.\n- Build caches stay honest: a cached task that copies screenshots hashes them\n through the link, or runs uncached (see [build caches](#build-caches)).\n- Document the prerequisites and output layout in the repository's own docs,\n and point agents at this skill from `AGENTS.md` in one sentence.\n\n## Layout\n\nUse one of two shapes, named by what consumes them:\n\n| Consumer | Layout | Example |\n| --- | --- | --- |\n| Website gallery or docs | `<layout>/<theme>/<screen>.png`, layouts `web`, `ipad`, `mobile`, themes `light`, `dark` | tearleads `.screenshots/mobile/dark/home.png` |\n| Store listings (fastlane) | `<platform>/<device>/<NN-screen>[-dark].png` | nc `.screenshots/ios/iphone/01-home.png` |\n\nScreen names are kebab-case and stable: a website keeps an allowlist and order\nof them, so renaming one is a change to both.\n\n## Web capture with Playwright\n\nThe pattern tearleads uses (`packages/app-web/playwright.screenshots.config.ts`\nand `packages/app-web/screenshots/`):\n\n- A separate Playwright config, so capture never runs in the e2e suite:\n `workers: 1`, `retries: 0`, a long test timeout, fixed `locale` and\n `timezoneId`.\n- One project per layout:\n - `web`: `viewport: { width: 1440, height: 900 }`, `deviceScaleFactor: 2`;\n - `ipad`: `...devices[\"iPad Pro 11\"]`;\n - `mobile`: `...devices[\"iPhone 13\"]` with `viewport` and `screen` set to\n `{ width: 390, height: 844 }`, the full phone screen of an installed app\n (1170x2532 PNGs). The profile's own 390x664 viewport is Safari's visible\n area and makes framed phones look too wide;\n - `browserName: \"chromium\"` for all three, so output does not depend on\n WebKit; the device profiles still give touch input, viewport, and scale.\n- Its own `webServer` entries on fixed, repository-specific ports with\n `reuseExistingServer: false`, against deterministic seed data or in-memory\n backends, never staging or production.\n- Each theme is pinned through the app's stored preference and a reload, then\n verified (for example on `data-theme`) before capturing.\n- Animations disabled with injected CSS after every navigation; wait for real\n readiness (data rendered, images decoded) instead of fixed sleeps.\n- `page.screenshot({ path })` for routed layouts, or an element screenshot for\n a windowed desktop app; `mkdir` the theme directory first.\n\n## Native capture with Maestro\n\nThe pattern nc uses (`scripts/testing/takeIosScreenshots.sh`,\n`takeAndroidScreenshots.sh`, `maestro/screenshots/`):\n\n- Dedicated, named simulators and emulators created on demand, so captures\n never depend on a day-to-day device's state; shut them down on exit.\n- Status bar overridden to 9:41, full signal, battery discharging at 100%\n (`xcrun simctl status_bar ... override`; Android demo mode).\n- Appearance set per capture (`xcrun simctl ui <udid> appearance dark`), with a\n short settle before the screenshot.\n- Maestro flows only navigate; the shell script takes the screenshot\n (`xcrun simctl io <udid> screenshot --mask=ignored`, `adb exec-out screencap`).\n- Validate every file: the exact store size for the device, and no alpha\n channel, which App Store Connect and Play reject.\n- Maestro's driver uses port 7001 for every device, so one Maestro run drives\n this machine at a time: check for a running `maestro` before starting.\n\n## Deploy guard and gallery\n\nA website that publishes screenshots stages them with\n`agent-tool screenshots build <target>` from the pinned `@a2f0/agent-tool`\n(0.1.32 or later), configured in the `screenshots` section of\n`agent-tool.json`, rather than its own copy script. It copies the allowlisted\n`<project>/<theme>/<screen>.png` files with content-hashed URLs and writes a\nmanifest, and it checks `.screenshots/capture.json` before and after copying.\nEvery capture writes a `running` record before it touches an image, so an\nunchanged `complete` record on both sides proves no capture overlapped the\ncopy. It refuses a capture that is not complete, names no commit, is\ndirty, or changed meanwhile, and a linked, non-empty store with no record\n(its images have no known commit, as after `link` moves an older capture into\nthe store). A missing or plain `.screenshots` (CI, an unlinked clone) builds\nwith what it holds, or an empty manifest.\n\nPages render that manifest with the package's framework-free elements from\n`@a2f0/agent-tool/screenshots/gallery` and its stylesheet:\n`<screenshot-gallery>` for a `/screenshots/[...slug]` route (deep links per\nproject and screen, a scrolling stage, a filmstrip, phone bezels) and\n`<screenshot-carousel>` for a looping row of every phone screen on a home\npage. Sites theme them with `--shots-*` custom properties. The package's\n`docs/screenshots.md` has the configuration, attributes, and an Astro example;\ntearleads and balebase are the references.\n\nA non-website consumer (a store upload) that copies captures itself must apply\nthe same before-and-after record check.\n\n## Build caches\n\nTurbo and similar caches hash declared inputs. A task that stages screenshots\nmust see changes made through the link: confirm that its input globs follow\nthe `.screenshots` symlink (recapture one screen and check the task misses its\ncache), or mark the staging task `cache: false`.\n",
|
|
55
|
+
"agents/openai.yaml": "interface:\n display_name: \"Take Screenshots\"\n short_description: \"Capture app screenshots once into the shared matrix-artifacts store\"\n default_prompt: \"Use $take-screenshots to check this repository's screenshots and capture them into the shared store if they are stale.\"\n"
|
|
46
56
|
}
|
|
47
57
|
};
|
package/src/system/checkouts.ts
CHANGED
|
@@ -5,8 +5,9 @@
|
|
|
5
5
|
* inherited `-c` setting never points it at another repository.
|
|
6
6
|
*/
|
|
7
7
|
import { spawnSync } from "node:child_process";
|
|
8
|
-
import { existsSync, readdirSync, realpathSync } from "node:fs";
|
|
8
|
+
import { existsSync, readdirSync, realpathSync, statSync } from "node:fs";
|
|
9
9
|
import path from "node:path";
|
|
10
|
+
import { assertOwnCheckout } from "../workflows/core";
|
|
10
11
|
|
|
11
12
|
// From `git rev-parse --local-env-vars`: variables that bind Git to one repository,
|
|
12
13
|
// such as those a hook sets, and that would override `-C`.
|
|
@@ -52,11 +53,23 @@ export function isolatedGit(cwd: string, args: string[]): { status: number | nul
|
|
|
52
53
|
return { status: result.status, stdout: result.stdout ?? "", ...(result.error ? { error: result.error } : {}) };
|
|
53
54
|
}
|
|
54
55
|
|
|
55
|
-
/**
|
|
56
|
+
/**
|
|
57
|
+
* The top level of the repository holding `cwd`, a directory or a file in one;
|
|
58
|
+
* undefined outside one. Throws when a nested checkout between them has a
|
|
59
|
+
* `.git` Git cannot read, since Git then answers for the enclosing repository.
|
|
60
|
+
*/
|
|
56
61
|
export function toplevel(cwd: string): string | undefined {
|
|
57
|
-
|
|
62
|
+
let directory = cwd;
|
|
63
|
+
try {
|
|
64
|
+
if (!statSync(cwd).isDirectory()) directory = path.dirname(cwd);
|
|
65
|
+
} catch {
|
|
66
|
+
return undefined;
|
|
67
|
+
}
|
|
68
|
+
const result = isolatedGit(directory, ["rev-parse", "--show-toplevel"]);
|
|
58
69
|
const top = result.stdout.trim();
|
|
59
|
-
|
|
70
|
+
if (result.status !== 0 || !top) return undefined;
|
|
71
|
+
assertOwnCheckout(top, directory);
|
|
72
|
+
return top;
|
|
60
73
|
}
|
|
61
74
|
|
|
62
75
|
/** A matrix workspace: `matrix.json` beside a `checkouts/` directory. */
|
|
@@ -87,8 +100,12 @@ export function workspaceCheckouts(workspace: string): Checkout[] {
|
|
|
87
100
|
.filter(entry => entry.isDirectory() && existsSync(path.join(workspace, "checkouts", entry.name, ".git")))
|
|
88
101
|
.map(entry => ({ name: entry.name, root: realpathSync(path.join(workspace, "checkouts", entry.name)) }))
|
|
89
102
|
.filter(checkout => {
|
|
90
|
-
|
|
91
|
-
|
|
103
|
+
try {
|
|
104
|
+
const top = toplevel(checkout.root);
|
|
105
|
+
return top !== undefined && realpathSync(top) === checkout.root;
|
|
106
|
+
} catch {
|
|
107
|
+
return false;
|
|
108
|
+
}
|
|
92
109
|
})
|
|
93
110
|
.sort((a, b) => (a.name < b.name ? -1 : a.name > b.name ? 1 : 0));
|
|
94
111
|
}
|
|
@@ -102,7 +119,12 @@ export function namedRoot(cwd: string, workspace: string | undefined, name: stri
|
|
|
102
119
|
const short = name.includes("/") && !existsSync(path.resolve(cwd, name)) ? name.split("/").pop()! : name;
|
|
103
120
|
if (workspace && existsSync(path.join(workspace, "checkouts", short, ".git"))) {
|
|
104
121
|
const root = realpathSync(path.join(workspace, "checkouts", short));
|
|
105
|
-
|
|
122
|
+
let top: string | undefined;
|
|
123
|
+
try {
|
|
124
|
+
top = toplevel(root);
|
|
125
|
+
} catch {
|
|
126
|
+
top = undefined;
|
|
127
|
+
}
|
|
106
128
|
// Git would answer for the enclosing workspace instead.
|
|
107
129
|
if (top === undefined || realpathSync(top) !== root) throw new Error(`checkouts/${short} is not a Git repository Git can read`);
|
|
108
130
|
return root;
|