@a2f0/agent-tool 0.1.72 → 0.1.74

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.
Files changed (36) hide show
  1. package/README.md +10 -8
  2. package/package.json +2 -1
  3. package/skills/performance-pass/SKILL.md +107 -0
  4. package/skills/performance-pass/agents/openai.yaml +4 -0
  5. package/skills/performance-pass/references/lessons.md +30 -0
  6. package/skills/space-cleanup/SKILL.md +96 -0
  7. package/skills/space-cleanup/agents/openai.yaml +4 -0
  8. package/skills/take-screenshots/SKILL.md +103 -0
  9. package/skills/take-screenshots/agents/openai.yaml +4 -0
  10. package/skills/take-screenshots/references/adding-capture.md +121 -0
  11. package/src/cli.ts +14 -1
  12. package/src/perf/browser.ts +269 -0
  13. package/src/perf/command.ts +82 -0
  14. package/src/perf/diff.ts +115 -0
  15. package/src/perf/graph.ts +110 -0
  16. package/src/perf/options.ts +107 -0
  17. package/src/perf/serve.ts +163 -0
  18. package/src/permissions/catalog.ts +6 -1
  19. package/src/screenshots/build.ts +4 -3
  20. package/src/screenshots/store/capture.ts +317 -0
  21. package/src/screenshots/store/clones.ts +145 -0
  22. package/src/screenshots/store/command.ts +317 -0
  23. package/src/screenshots/store/git.ts +14 -0
  24. package/src/screenshots/store/link.ts +201 -0
  25. package/src/screenshots/store/lock.ts +94 -0
  26. package/src/screenshots/store/namespace.ts +311 -0
  27. package/src/screenshots/store/record.ts +157 -0
  28. package/src/screenshots/store/store.ts +47 -0
  29. package/src/screenshots/store/targets.ts +68 -0
  30. package/src/skills/bundled.ts +14 -0
  31. package/src/space/candidates.ts +228 -0
  32. package/src/space/command.ts +325 -0
  33. package/src/space/machine.ts +303 -0
  34. package/src/space/processes.ts +186 -0
  35. package/src/space/targets.ts +24 -0
  36. package/src/system/checkouts.ts +135 -0
@@ -6,10 +6,13 @@ 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
+ "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",
9
10
  "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",
10
11
  "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",
11
12
  "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
+ "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",
12
14
  "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",
15
+ "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",
13
16
  "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"
14
17
  };
15
18
  /** 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. */
@@ -29,10 +32,21 @@ export const BUNDLED_SKILL_REFERENCES: Readonly<Record<string, Readonly<Record<s
29
32
  "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",
30
33
  "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"
31
34
  },
35
+ "performance-pass": {
36
+ "references/lessons.md": "# Performance lessons\n\nCross-repository findings from performance passes, newest first. Each names\nthe repository and PR it came from; recheck before relying on one.\n\n## Layers that change nothing until used can wait for first use\n\nskyline built its colour-trial layer, which reads every vertex of every\nbuilding, before the first frame, though its shaders install only when colour,\na previewed time or a celebration is used. Making it on first use (and before\na celebration rewrites the greys it reads) took its 160 to 270 ms off the\nfirst frame, pixel-identical in seven before/after interaction shots.\n\n## Unbundled ES module graphs pay one round trip per import level\n\nskyline (a2f0/skyline) ships tsc output without a bundler, so the viewer's\nfirst frame waited on a chain seven requests deep. Listing the graph at build\ntime and preloading it with `modulepreload` from the mounting code moved\nnetwork-done from 1471 to 833 ms and the ready median from 2369 to 1763 ms at\n40 ms / 20 Mbps (5204 to 4514 ms on the slow profile), pixel-identical with\nthe random stars hidden. Generate the list from the built files so it cannot\ndrift, leave out modules the host may replace, and expect a host-bundle size\nbudget to need room for the preloading code.\n\n## Seeded randomness still drifts when load order changes\n\nThree.js draws object UUIDs from `Math.random`, so a seeded page that builds\nits scene earlier or later relative to random decoration (skyline's stars)\nshows that decoration elsewhere. Hide the decoration with `shot --hide` and\ndiff the rest; two base shots must still diff to zero first.\n",
37
+ "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"
38
+ },
32
39
  "seo-optimization": {
33
40
  "references/cloudflare-workers.md": "# Cloudflare Workers hosting\n\nCheck these against the current\n[static assets documentation](https://developers.cloudflare.com/workers/static-assets/)\nwhen behavior matters; wrangler versions change details. Everything here was\nobserved on live Workers in 2026 with wrangler 4.\n\n## Static asset headers\n\n- `_headers` in the assets directory applies to every hostname of that\n Worker. A tier-specific header therefore needs a tier-specific build, or a\n deploy step that writes the file for each environment.\n- Rules are keyed by path pattern, so a second block with the same pattern\n replaces the first block's headers instead of adding to them. Appending a\n separate `/*` noindex block can silently drop security or cache headers;\n add `X-Robots-Tag` inside the existing `/*` rule.\n- Rules with different patterns merge. When two matching rules set the same\n header, the response carries it twice, so do not add a path rule for a\n header that `/*` already sets on that tier. `/x/*` matches `/x/` and below\n but not `/x`; add both patterns to cover the redirecting form.\n- A `/*` rule reaches everything the asset handler answers: HTML, assets,\n the `html_handling` 307 redirects, single-page fallbacks, 404 responses,\n and robots.txt, including the zone's managed robots.txt when the origin has\n none.\n- `_headers` does not apply to responses a Worker script generates, such as\n its own redirects, sign-in pages, or dynamic routes. A Worker with a `main`\n script needs the header set in code, driven by a tier variable in the\n wrangler `env`. With `run_worker_first: true`, `_headers` never applies;\n set the header in one wrapper around the router so every response gets it.\n- `_headers` itself is never uploaded as an asset or served. Leave it out of\n any deploy check that lists the built files, and out of published packages.\n- An authentication gate redirects robots.txt to the sign-in page unless the\n file is on the gate's public allowlist.\n- `:name` placeholders match exactly one path segment and `*` matches the\n rest. A `! Header-Name` line detaches a header that an earlier matching rule\n set; it only works when it comes after that rule. A file has a limit of 100\n rules, so a build that generates rules per file should fail before reaching\n it.\n\n## URLs and status codes\n\n- `html_handling: \"auto-trailing-slash\"`, the default, answers the other form\n with a 307, so canonical URLs and internal links must use the form that is\n served directly. That form follows the file layout: `page/index.html` is\n served at `/page/`, and a flat `page.html` at `/page`, even when a `page/`\n directory exists; `/page.html` redirects too. `drop-trailing-slash` always\n serves the form without the slash.\n- `not_found_handling: \"none\"`, the default, answers unknown paths with a 404\n and an empty body. On content hosts, add a `404.html` and switch to\n `\"404-page\"` so visitors get a helpful page.\n- `\"404-page\"` serves the nearest `404.html` up the path with status 404,\n including for missing assets such as `/data/x.json`, which then receive\n `text/html`; that is fine for code that checks `response.ok`.\n `/404.html` itself redirects to `/404`, which answers 200, so the error\n page needs a robots noindex, and tests should use a missing path rather\n than the error page's own URL.\n- `\"single-page-application\"` answers every unknown path with the app shell\n and a 200, a soft 404. It also answers `/robots.txt` and `/sitemap.xml`\n with HTML unless real files exist. Switch to `\"404-page\"` only when nothing\n depends on client-side routing.\n- With a `main` script, the asset 404 page comes through `env.ASSETS.fetch`,\n while paths routed to the script first keep the script's own 404.\n- A Worker that redirects every unmatched path, for example to keep old app\n links working, also redirects robots.txt and the sitemap. Generate both as\n build assets so the asset handler answers them first.\n- A repository's deploy guard may pin the Worker's asset configuration.\n Update the guard with the change, and run its preview on the exact commit.\n\n## Testing on the real runtime\n\n- Development servers such as `vite preview` answer every path with the app,\n so status and header tests must run against `wrangler dev` or a deployed\n Worker. A test that only matches text in the configuration does not prove\n the behavior.\n- A test can spawn `wrangler dev --config <config> --local --ip 127.0.0.1\n --port 0 --inspector-port 0 --persist-to <tmp>\n --show-interactive-dev-session=false`, adding `--assets <build>` when the\n configuration does not name the build directory. `_headers` and the\n configured `not_found_handling` apply, so status codes and the\n non-production `X-Robots-Tag` can be checked end to end. Details that\n matter:\n - spawn it with Node; under `bunx --bun` workerd has been seen to accept\n connections and never answer;\n - strip ANSI codes before matching the `Ready on` line, and keep draining\n stdout and stderr so the pipes do not fill;\n - set `WRANGLER_SEND_METRICS=false` and point `WRANGLER_LOG_PATH` at the\n temporary directory; it still writes a gitignored `.wrangler/tmp`;\n - stop it with SIGTERM, then SIGKILL;\n - prove the test by reverting the setting and watching it fail.\n- `wrangler dev` reloads an edited `_headers` without a restart, which makes\n checking merged rules cheap.\n- Deploying the branch to the non-production tier before merging is a cheap\n way to confirm routing, headers, and status codes on the real runtime.\n\n## Duplicate hosts\n\nEvery Worker can also answer at `<worker>.<subdomain>.workers.dev` and at\nper-version preview hosts, `<first 8 characters of the version ID>-<worker>.<subdomain>.workers.dev`.\nBoth serve full copies of the site.\n\n- Set `workers_dev: false` and `preview_urls: false` in every environment\n unless something depends on those URLs: check API base URLs, CORS and\n authentication origins, docs, tests, and CI first.\n- When the configuration has no `routes`, for example because Terraform binds\n the custom domain, wrangler enables `workers_dev` by default. An unset\n `preview_urls` leaves the existing setting alone, so preview hosts can be\n live despite the documented default.\n- When `workers_dev` is on, the deploy output names the `workers.dev` URL;\n probe it and a preview host before and after. With an explicit `false` in\n every environment, a deploy whose output names no `workers.dev` target is\n enough evidence. A disabled or missing Worker on a valid subdomain answers\n error 1042, so a probe cannot tell the two apart. When API credentials are\n already available, the read-only\n `GET /accounts/{id}/workers/scripts/{name}/subdomain` returns `enabled` and\n `previews_enabled`; never read an OAuth token out of wrangler's\n configuration to call it.\n\n## Zone settings and redirects\n\n- Zone-wide settings, such as `always_use_https`, belong to exactly one\n Terraform stack, usually production, never a module that both tiers use.\n The Cloudflare provider cannot destroy a `cloudflare_zone_setting`:\n removing it from Terraform leaves the setting as it is.\n- Before turning on Always Use HTTPS, check that nothing depends on plain\n HTTP: API base URLs in web, desktop, and native clients, webhook endpoints\n registered with providers such as Stripe (list them read-only), and OAuth\n or payment return URLs. Providers rarely follow a redirect on a webhook\n POST.\n- A `www` to apex redirect needs no origin: a proxied `AAAA` record for `www`\n with content `100::`, and a `cloudflare_ruleset` in phase\n `http_request_dynamic_redirect` whose rule matches\n `http.host eq \"www.<zone>\"` and answers 301 with\n `concat(\"https://<zone>\", http.request.uri.path)`, preserving the query\n string. Universal SSL already covers `www`. Single redirects run before\n Workers, so the rule works even while `www` is still a Worker custom\n domain.\n- A zone has one ruleset per phase: extend or import an existing one.\n- The redirect needs the token permission Zone → Single Redirect → Edit\n (\"Dynamic URL Redirects Write\"). A token without it gets\n `403 request is not authorized` even when reading the phase entrypoint, so\n read it first and stop before writing Terraform the token cannot apply.\n Never widen a token's permissions yourself.\n- When the user authorizes it, the `cf` CLI, signed in as the account owner,\n can create the rule (`cf rulesets entrypoint update\n http_request_dynamic_redirect -z <zone> --name Redirects --rules\n @rules.json`, with `--validate-only` first) and the record\n (`cf dns records create`). Document such configuration in the repository:\n what exists, how to recreate it, and that Terraform must import it later.\n- Repositories whose apply step refuses plans that delete resources need an\n explicit decision before a change that removes a custom domain.\n\n## Cloudflare's managed robots.txt\n\nA zone can serve a Cloudflare-managed robots.txt. Observed behavior:\n\n- a zone with only the content-signals policy serves a comments-only file\n when the origin has no robots.txt, and the origin file replaces it\n entirely;\n- a zone that also manages AI-crawler rules prepends its block, with\n `Content-Signal` and `Disallow` directives, to the origin file, and serves\n it alone where the origin answers 404;\n- where the origin answers `/robots.txt` with a 404, the managed file is\n served with status 200 and keeps the origin's other headers, including an\n `X-Robots-Tag` from `_headers` or Worker code;\n- a single-page fallback that answers `/robots.txt` with HTML suppresses\n either file.\n\nBefore serving your own file, record which directives were live, such as\n`Content-Signal` lines or `Disallow` rules for AI crawlers. Keep their effect\nin the origin file, or ask the user. Comments-only managed files carry no\ndirectives. Do not change the zone setting without explicit authorization.\n\n## Deploys and verification\n\n- Merging is not deploying in many repositories: they deploy by hand with an\n existing `wrangler login` session or documented credentials. Check the\n deploy docs and confirm the new version is live. Custom domains owned by\n Terraform make `wrangler deploy` report no targets deployed; that is\n normal.\n- A manual deploy ships everything merged since the last one, so find out\n what is live first, check again just before deploying, and report what else\n went live. Compare pages at the URLs they are served from (`/`, not\n `/index.html`, which redirects with an empty body), and compare with a\n plain client: the zone may inject scripts, such as an analytics beacon,\n only for browser user agents.\n- `wrangler deployments list` shows times and version IDs but usually no\n commit. `_headers` is not served, so compare its rules with live response\n headers rather than bytes. In wrangler's output, \"Uploaded N (M already\n uploaded)\" counts assets; \"Read N files\" also counts directories. Passing\n `--message <commit>` to `wrangler deploy` makes later comparisons easy;\n suggest it rather than adding it unasked.\n- A hostname that does not resolve may belong to a Terraform stack that a\n teardown destroyed and no deploy re-applies. Check that stack's state with\n a read-only plan before assuming a DNS fault, and check that the content\n behind it, such as uploaded release files, exists too.\n- A manual deploy can build from gitignored local inputs, such as captured\n screenshots or generated data. Compare them with what is live before\n deploying, so a stale local copy does not regress production.\n- A configuration change to an API Worker, even `workers_dev`, is an API\n release that may pull in migrations, secrets, and infrastructure steps.\n Check pending migrations first (for D1,\n `wrangler d1 migrations list <database> --remote`).\n- Some repositories deploy staging from a branch such as `staging`. Moving it\n is a deploy, so do it only when deploying is authorized and the\n repository's docs name that branch as the staging trigger: fast-forward\n only, never force, and report how far it moved.\n- \"Always Use HTTPS\" is a zone setting. When `http://` answers 200 instead of\n redirecting, record it rather than changing the zone, and say where the fix\n belongs: Terraform can manage it as a `cloudflare_zone_setting` with\n `setting_id = \"always_use_https\"`, so check whether the repository or a\n sibling repository already does.\n",
34
41
  "references/frameworks.md": "# Framework notes\n\n## Astro\n\n- Inject the tier with `vite.define` on an `import.meta.env.PUBLIC_*` value,\n so `astro.config.*` and the pages agree on it. Astro integrations do not\n receive `--mode`; record it from a Vite plugin's `configResolved` hook, and\n throw when it is missing.\n- Write JSON-LD with\n `<script is:inline type=\"application/ld+json\" set:html={json}>` and escape\n `<` as `\\u003c` in the serialized JSON.\n- When conditional tags go into a named slot, wrap them as\n `<Fragment slot=\"head\">{condition && …}</Fragment>` rather than putting the\n condition around an element that carries `slot=`. Test that the output\n lands inside `<head>`.\n- In `astro:build:done`, page pathnames look like `\"\"`, `\"privacy/\"`, and\n `\"404/\"`. Filter error pages out of the sitemap. `@astrojs/sitemap` works,\n or a small integration can write `sitemap.xml` and `robots.txt` from the\n built pages.\n- Knip treats `astro.config.*` as plugin configuration, so a new integration\n file it imports may need to be listed as a production entry.\n\n## Next.js static export\n\n- A page that renders only on the client (`autoExport` with an empty\n `<div id=\"__next\">`) gives crawlers nothing. `next/head` tags in a\n statically exported page do reach the HTML; the main copy needs build-time\n rendering, which is content work.\n- With the pages router, put tier-wide tags such as the staging robots meta\n in `_document.tsx`, so `404.html` gets them too. Inline the tier through\n `next.config` `env` so the browser hydrates with the same tags; otherwise\n `next/head` can add or drop them on the client.\n- Do not import relative TypeScript into `next.config.ts`.\n- Add an explicit `pages/404.tsx` so the error page's head (noindex, no\n canonical, no `og:url`) is under the app's control, and pair it with\n `not_found_handling: \"404-page\"` when missing paths should get it.\n- When two `next/head` instances emit the same tag, whichever re-rendered\n last wins, even with matching `key`s. Keep one owner for a dynamic tag such\n as `theme-color`. When the theme provider renders on the client below\n `<Head>`, read the attribute it stamps on `<html>` instead.\n- `next build` clears `out/`, so write `robots.txt`, `sitemap.xml`, and\n `_headers` after it. With a single-page fallback on the host, a missing\n file is answered with HTML.\n\n## Monorepo tooling\n\n- Turborepo strict environment mode drops undeclared variables, so declare a\n tier variable in `turbo.json` `env`. Declaring it also keeps the two tiers'\n caches apart.\n- In a package script, `VAR=x a && b` sets the variable for `a` only.\n- A broad ignore pattern such as `build/` can also match a new\n `scripts/build/` file, so `git add -A` silently skips it. Run\n `git check-ignore` on new files.\n- A production check of \"no noindex anywhere\" fails when a site copies\n deliberately noindexed pages from a package. Check the header rules and the\n pages the site owns.\n- When a package's pages are copied into another site, give them absolute\n canonical, `og:url`, and JSON-LD URLs on their own production host, never\n derived from the request host, so the copies point back to the original.\n Keep robots.txt, the sitemap, the preview image, and the 404 page out of\n the package; they belong at the deployment root. Any change to files in\n the published tarball follows the repository's versioning policy, and the\n report names the release a consuming site needs.\n- Tests that fetch every `src` and `href` in a page will fetch an absolute\n canonical from the live network; filter them to relative references.\n\n## Theme-color with a theme switch\n\nKeep one owner for the tag. The simplest owner is the script that applies the\nsaved theme before first paint: let it write `theme-color` and watch the\ntheme attribute it sets (for example `data-theme` on `<html>`), so framework\ncomponents never write the tag.\n\n## Runtime titles\n\nCode that sets `document.title` after load, such as the name of an open\ndocument, replaces the static title that crawlers which run JavaScript index.\nSearch for `document.title` before writing a static title. When the product\nbehavior must stay, use the form `<document> · <what the page is> · <brand>`;\nthe brand alone is not descriptive. Check whether the title callback is part\nof a published API before changing it, and read the rendered title in a\nheadless browser after the app mounts, not at the load event.\n\n## Vite single-page apps\n\n- Put static tags in `index.html`. For tier-conditional tags, use a plugin\n hook such as `transformIndexHtml`, or `vite-plugin-html`'s `inject.tags`.\n EJS scriptlets in `index.html` can break linters that parse HTML, such as\n Biome.\n- The public directory is copied before `writeBundle`, so a plugin can edit\n the built `_headers` there. Insert into the existing `/*` rule.\n- An extensionless relative import in `vite.config.ts` can trigger Vite's\n native config loader warning; keep small plugins inline or use an explicit\n extension.\n- To give a client-routed site per-route metadata without a framework\n change, list the routes once and write one copy of the app shell per route\n (for example `company.html`) with that route's tags. Then switch the host to\n a 404 page that is the same shell, so client routing still works. Every\n routed path needs its own document, including flag-gated and nested routes,\n or a reload of that path returns 404.\n- Model the head tags once, render them at build time, and reapply them on\n client navigation. Updating only `document.title` leaves a stale canonical,\n description, and robots tag; reviewers rate that as a major finding.\n\n## Bun's HTML bundler\n\nIt leaves absolute canonical and Open Graph URLs and JSON-LD blocks\nuntouched, so static tags in the source HTML survive the build.\n\n## react-native-web\n\n- The page is empty until the bundle runs; record that as a recommendation\n when you cannot prerender a static summary.\n- `accessibilityRole=\"header\"` renders an `<h1>` with no visual change and\n marks the heading for native screen readers.\n\n## Service workers\n\nApply tier-specific tags after the build but before the precache manifest\nis generated, so the cached shell matches its tier.\n\n## Preview images with agent-tool\n\nRender `og-image.png` with `agent-tool images` from `assets/brand/` sources:\nan output with `\"size\": [1200, 630]`, a background or fill layer, and the logo\nlayer. The renderer loads no fonts, so the image cannot contain text unless\nit is converted to paths. Choosing the target:\n\n- Default to a separate target, such as `social`, beside `favicons`, and\n follow `dir` targets when the repository already uses them.\n- Extending an existing target is fine when only one package uses it and no\n test ties it to the linked icons; a target shared by several packages\n through `--out` would put the image in every package's build.\n- Check service worker precache globs: a PNG in a precached `public/` folder\n bloats the offline cache.\n- `build --out <dir>` takes exactly one target and an absolute or\n repository-relative directory. Repositories that ban committed binaries\n render the image during the build, production only if it is tier-specific.\n\nSources must meet agent-tool's rules in its `docs/images.md`: `<title>`,\n`<desc>`, and `<metadata>` are allowed, while `<style>`, `style` attributes,\ntext, and elements from editor namespaces are not. The practical test is\nwhether `agent-tool images build` succeeds. When the only logo is an editor\nexport that fails, record the needed plain SVG instead of rendering from it.\n",
35
42
  "references/standard.md": "# Standard by host class\n\nRead \"Every host\" and the sections for the host classes you found. Sources\nworth opening when a rule matters:\n[Google Search Central](https://developers.google.com/search/docs),\n[robots meta and X-Robots-Tag](https://developers.google.com/search/docs/crawling-indexing/robots-meta-tag),\n[canonical URLs](https://developers.google.com/search/docs/crawling-indexing/consolidate-duplicate-urls),\n[sitemaps](https://www.sitemaps.org/protocol.html),\n[structured data policies](https://developers.google.com/search/docs/appearance/structured-data/sd-policies),\nand [the Open Graph protocol](https://ogp.me/).\n\n## Every host\n\n- Every HTML page carries one `theme-color` that matches its top chrome, or\n its background when it has no header, in each theme. When views differ, use\n the first view a visitor sees, such as the sign-in page.\n- When an in-app appearance toggle changes that color, the tag must follow it\n at runtime, not only through `prefers-color-scheme` variants, and exactly\n one piece of code may own it. This is browser chrome, not ranking: when\n following an app's own theme system needs app UI work, record it as a\n recommendation instead.\n- Hosts that this repository's infrastructure binds but another repository\n builds and deploys belong to that repository's pass.\n\n## Non-production tiers\n\nA repository with only a production tier skips this section, but still\nchecks the platform's duplicate hosts, such as `*.workers.dev`.\n\n- Send `X-Robots-Tag: noindex, nofollow` on every response, including assets,\n fallbacks, error pages, redirects, and robots.txt. A non-production API host\n that answers only JSON follows the API rule under\n [Internal hosts](#internal-hosts).\n- Put `<meta name=\"robots\" content=\"noindex, nofollow\">` in every HTML\n document, so a copied or cached page still carries it.\n- Keep robots.txt crawlable. A missing file or a comments-only managed file\n already is; add or change a file only to remove a `Disallow`. A\n `Disallow: /` stops crawlers from fetching pages, so they never see the\n noindex and can still index a linked URL without its content.\n- Emit no `<link rel=\"canonical\">`, `og:url`, sitemap, or Sitemap line; those\n tell crawlers which URL to index. Other preview tags and structured data may\n stay, including `og:image` at the tier's own host or at production, so that\n shared staging links still preview.\n- A zone-level redirect, such as HTTP to HTTPS, is answered before the\n application and cannot carry the header. Record it; the target carries the\n header.\n- Derive the tier from the mechanism the repository already uses, such as a\n wrangler `env`, a build mode, or a release tier variable. Make the\n production build the explicit choice, fail on an unknown tier, and test\n both outcomes. When one artifact is promoted between tiers, apply the tier\n at deploy time, for example by writing `_headers` per environment, rather\n than breaking promotion.\n- Leave an already-compliant tier unchanged after verifying it.\n\n## Content hosts\n\n1. **Static head.** The HTML served before JavaScript runs carries:\n - a unique `<title>` that names what the page is, with the brand (the\n product, or the person or site name on a personal site) last, kept under\n about 60 characters;\n - `<meta name=\"description\">` of up to about 160 characters, written from\n the page's own copy;\n - `<link rel=\"canonical\">` with the absolute production URL in the exact\n form the host serves without redirecting (trailing slash or not);\n - `<html lang>`, the viewport tag, and `theme-color`.\n\n The lengths are limits on what search results show, not targets: a short\n title that names a person or a page is fine, and padding with invented\n copy is not. Shortening an over-long description by choosing from its own\n sentences is a metadata edit; when it would need new wording, record it. A\n page that sets its title only from JavaScript needs static or prerendered\n metadata. When the app localizes text in the browser, localize a\n descriptive `document.title` too.\n2. **Previews.** Add `og:type`, `og:site_name`, `og:title`,\n `og:description`, `og:url` (equal to the canonical), `og:image` (an\n absolute URL to a 1200×630 PNG), `og:image:width`, `og:image:height`,\n `og:image:alt`, and `twitter:card` = `summary_large_image`. Twitter falls\n back to the Open Graph title and description. Without a usable image, omit\n `og:image` and use `twitter:card` = `summary`.\n3. **Structured data.** Add JSON-LD in `<script type=\"application/ld+json\">`:\n - `WebSite` on every content host's home page, and `Organization` when the\n site names its publisher;\n - `SoftwareApplication` or `WebApplication` for a product, with\n `operatingSystem` listing only platforms a visitor can use today and\n `offers` only for prices the site already states;\n - `Person` for a resume, using only facts on the page.\n\n Escape `<` inside the JSON, and parse it in a test. Never add ratings or\n reviews that are not on the page.\n4. **robots.txt.** Serve a real `text/plain` file with `User-agent: *`,\n `Allow: /`, any deliberate existing rules, and\n `Sitemap: https://<host>/sitemap.xml`. Keep earlier directives that had an\n effect, such as AI-crawler rules or `Content-Signal` lines, unless the user\n decides otherwise.\n5. **Sitemap.** List the absolute canonical URL of every indexable page and\n nothing else: no error pages, redirects, placeholder pages, or\n non-production hosts. Generating it from the canonical links in the built\n HTML keeps the two from drifting.\n6. **Status codes.** An unknown path returns 404 with a helpful page when the\n platform allows it; an empty 404 body is a gap. Do not remove a fallback\n that client-side routing or old-link redirects depend on; record the soft\n 404 instead. The site should redirect `http://` to `https://`; when that is\n a CDN or zone setting, record it.\n7. **Error page.** The same error page is served at any depth, so its links\n and assets need root-relative paths. Hosts often answer its own path (such\n as `/404`) with 200, so give it a robots noindex and no canonical, `og:url`,\n or sitemap entry; it is the one production page that carries noindex.\n Leave analytics off it when it can answer under paths with stricter privacy\n promises (a zone may still inject its own), and make the local development\n server answer missing paths the same way.\n8. **Internal links.** Every link to the site's own pages uses the canonical\n form, so following it answers 200 without a redirect;\n `agent-tool seo probe --links` finds the others. Add a build test that\n fails on a link that would redirect or miss, generating any gitignored\n build assets it reads first.\n Changing link forms can break code that compares links with the current\n path, such as an active-page marker. Shared link constants in other\n packages count too, and changing them can require those packages' version\n bumps.\n9. **Hygiene on touched pages.** One `<h1>` that names the page (not one\n shared by a whole gallery), meaningful `alt` text on content images, and\n descriptive link text. On image-heavy pages, keep only the likely Largest\n Contentful Paint image eager, with `fetchpriority=\"high\"`, and lazy-load\n the rest with explicit `width` and `height`.\n10. **Manifest.** Where a web app manifest exists, make the name, short name,\n description, icons, colors, `start_url`, and `display` accurate. Add\n `related_applications` only after the store listings exist.\n11. **Copied pages.** When a site serves copies of another project's pages,\n for example from a package's asset folder, the copies should canonicalize\n to the original host. That is the producer's change: absolute canonical\n and `og:url` values in the pages it ships. On the consuming side, upgrade\n to a release whose tarball you have checked for the change, and review\n the API between the old and new versions first. Copies of pages that are\n deliberately kept out of search keep the producer's robots rules, but\n their assets can still be indexed: add a path-scoped `X-Robots-Tag` rule\n for the copied directory in production, where no `/*` rule already sends\n it, and respect any deploy guard the consumer has. Probe asset paths under\n the copy, not only its pages.\n\nPaths on a content host that are not meant for search, such as review or\npreview pages, get the internal-host treatment: the header, the robots meta,\nand no sitemap entry. Placeholder pages without real copy do too, through a\nflag on the page, so a page becomes indexable and joins the sitemap as soon\nas it gets content.\n\nWhen several sites belong to one company, give them the same `Organization`\nnode, with the same `@id`, name, legal name, URL, and logo, and point\n`publisher` or `provider` at that `@id`.\n\n## App hosts\n\n- Replace a generic shell title such as \"App\" with the product name and what\n it is, for example \"Tearleads – Encrypted notes, contacts, and files\". Add a\n description and Open Graph tags.\n- Reuse the product's preview image by pointing `og:image` at the content\n host's absolute URL rather than rendering a second copy, and deploy the\n content host first when the image changes. Requesting the image path on the\n app host itself may return the shell; check the URL the page names.\n- Serve a real `text/plain` robots.txt. A single-page fallback otherwise\n answers it with HTML.\n- Add a canonical pointing at the app root only when every route shows the\n same shell. When the app has distinct public, shareable routes, such as user\n pages or published documents, a root canonical marks them as duplicates.\n Omit the canonical and record whether those routes should be indexable. That\n is a product and privacy decision, because sharing by link is not consent to\n search listing.\n- A host that serves a duplicate of another host's app, such as a demo build,\n canonicalizes to the primary app root.\n- Once the product owner decides that public user-content routes stay out\n of search, noindex them with a path rule. If those routes cannot be told\n apart from app routes by URL pattern (for example `/:user` and `/admin`),\n send the header on every path below the root, detach it on built files,\n and keep the root indexable; say so in the report, because it also covers\n app routes. Add the robots meta in the view as well, never twice. Without\n that decision, record the question instead of noindexing anything.\n- Private links that work without an account, such as signing or sharing\n URLs with a token, get `X-Robots-Tag: noindex, nofollow` through a path\n rule, while the rest of the app keeps its canonical. Files those pages link\n to on an API host, such as PDF downloads, should carry the header too.\n- The content-host rule for localized titles applies to app hosts that\n localize in the browser.\n\n## Internal hosts\n\nAdmin dashboards, galleries, package viewer sites, and other HTML surfaces\nthat are not meant for search follow every non-production rule above: the\nheader (`noindex, nofollow`) on every response, including server-generated\nredirects and sign-in pages; the robots meta in the HTML; a crawlable\nrobots.txt; and no canonical, `og:url`, or sitemap. Empty preview and\nstructured-data results are expected on these hosts.\n\n- API hosts that answer only JSON need nothing unless adding the header is\n trivial and leaves CORS and other behavior unchanged. On any tier, files\n they serve behind private links do need it.\n- An existing `noindex` robots meta can stay as it is; the header carries\n `nofollow`. Do not change meta tags in pages that a package ships for other\n sites to copy, because the copies take them along. Keep host-only files such\n as `_headers` out of the package.\n- A host with one tier has no tier switch to test. Test that every page has\n the robots meta and no canonical, and that the header is present: the rule\n in the deployed build for static assets, or a unit test of the wrapper when\n a Worker sets it in code. In a repository that also publishes the pages as\n a package, test that the package leaves the host-only header file out.\n- When the repository has a verification script or a documented post-deploy\n check for the site, add the live header check there. Do not add SEO checks\n to gates for other releases, such as a package publishing gate.\n\n## Apps that will ship to stores\n\nUntil the store listings are live, list only `Web` in `operatingSystem`, and\ndo not add smart app banners, `related_applications`, or new links to store\npages that answer 404. Existing store links may reflect an owner's decision,\nso search the PR history and record a conflict rather than removing them.\n\nRecord what the launch needs: the App Store ID for `apple-itunes-app`, the\nPlay package for `related_applications`, store links in static HTML, offers\nthat match the listing, and, only if deep links are wanted,\n`apple-app-site-association` (Team ID and bundle ID) and `assetlinks.json`\n(the Play app signing certificate's SHA-256).\n",
36
43
  "agents/openai.yaml": "interface:\n display_name: \"SEO Optimization\"\n short_description: \"Audit and fix search metadata and staging noindex\"\n default_prompt: \"Use $seo-optimization to audit this repository's websites and fix their search and link-preview metadata, keeping staging out of search.\"\n"
44
+ },
45
+ "space-cleanup": {
46
+ "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"
47
+ },
48
+ "take-screenshots": {
49
+ "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",
50
+ "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"
37
51
  }
38
52
  };
@@ -0,0 +1,228 @@
1
+ /** Which ignored paths in a repository are regenerable, and which must be kept. */
2
+ import { spawnSync } from "node:child_process";
3
+ import { existsSync, lstatSync, type Stats } from "node:fs";
4
+ import path from "node:path";
5
+ import { isolatedGit } from "../system/checkouts";
6
+
7
+ /** Git bound to the repository it is asked about, whatever the caller's environment. */
8
+ function git(root: string, args: string[]): { ok: boolean; stdout: string } {
9
+ const result = isolatedGit(root, args);
10
+ return { ok: result.status === 0, stdout: result.stdout };
11
+ }
12
+
13
+ export const TIERS = ["caches", "builds", "deps"] as const;
14
+ export type Tier = (typeof TIERS)[number];
15
+
16
+ /** Tool and test caches: rebuilt on the next run at little cost. */
17
+ const CACHE_NAMES = new Set([
18
+ ".turbo",
19
+ ".parcel-cache",
20
+ ".eslintcache",
21
+ ".stylelintcache",
22
+ "coverage",
23
+ ".nyc_output",
24
+ "test-results",
25
+ "playwright-report",
26
+ "blob-report",
27
+ "__pycache__",
28
+ ".pytest_cache",
29
+ ".mypy_cache",
30
+ ".ruff_cache",
31
+ ]);
32
+ /** Build outputs: rebuilt by the repository's build, which can take minutes. */
33
+ const BUILD_NAMES = new Set(["dist", "build", "out", ".next", ".nuxt", ".output", ".svelte-kit", ".expo", ".gradle", ".build", "DerivedData"]);
34
+ /** Installed dependencies: restored by the repository's documented install. */
35
+ const DEPS_NAMES = new Set(["node_modules", ".venv"]);
36
+ /** Regenerable children of ignored directories that are themselves kept by a lighter tier. */
37
+ const NESTED: Record<string, Array<[string, Tier]>> = {
38
+ node_modules: [
39
+ [".cache", "caches"],
40
+ [".vite", "caches"],
41
+ ],
42
+ ".next": [["cache", "caches"]],
43
+ // .wrangler/state holds local D1, KV, and R2 data; only tmp is disposable.
44
+ ".wrangler": [["tmp", "caches"]],
45
+ vendor: [["bundle", "deps"]],
46
+ };
47
+
48
+ /** The tier a git-ignored path belongs to, or undefined when it is not known to be regenerable. */
49
+ function classify(rel: string, root: string): Tier | undefined {
50
+ const name = path.posix.basename(rel);
51
+ const parent = path.join(root, path.posix.dirname(rel));
52
+ if (CACHE_NAMES.has(name)) return "caches";
53
+ // Small, but deleting one makes the next typecheck start from scratch.
54
+ if (BUILD_NAMES.has(name) || name.endsWith(".tsbuildinfo")) return "builds";
55
+ if (name === "target" && existsSync(path.join(parent, "Cargo.toml"))) return "builds";
56
+ if (DEPS_NAMES.has(name)) return "deps";
57
+ if (name === "Pods" && existsSync(path.join(parent, "Podfile"))) return "deps";
58
+ // Bundler's install path, ignored on its own beside a tracked vendor/.
59
+ if (name === "bundle" && path.posix.basename(path.posix.dirname(rel)) === "vendor") return "deps";
60
+ return undefined;
61
+ }
62
+
63
+ /** Ignored paths from `git status --porcelain=v1 -z --ignored`, without trailing slashes. */
64
+ export function parseIgnored(porcelain: string): string[] {
65
+ return porcelain
66
+ .split("\0")
67
+ .filter(entry => entry.startsWith("!! "))
68
+ .map(entry => entry.slice(3).replace(/\/$/, ""));
69
+ }
70
+
71
+ export interface Candidate {
72
+ readonly path: string;
73
+ readonly tier: Tier;
74
+ bytes: number;
75
+ }
76
+
77
+ /** Names that mark a tree as holding work or data rather than regenerable output. */
78
+ // `.env*` covers `.envrc` and `.env-production` as well as `.env.local`.
79
+ const PROTECTED = [".git", ".env*", ".secrets", "*.sqlite", "*.sqlite3", "*.db"];
80
+ const TEMPLATE = /\.(example|sample|template)$/;
81
+ /**
82
+ * The llbuild databases Xcode (`Build/Intermediates.noindex/XCBuildData/build.db`, in DerivedData
83
+ * or a `build/` directory) and SwiftPM (`.build/build.db`) write beside their output.
84
+ */
85
+ const BUILD_DATABASES = ["*/XCBuildData/build.db", "*/.build/build.db"];
86
+
87
+ /** Whether one path component is protected, by the same patterns `find` applies below. */
88
+ export function protectedName(name: string): boolean {
89
+ if (TEMPLATE.test(name)) return false;
90
+ return PROTECTED.some(pattern =>
91
+ pattern.startsWith("*.") ? name.endsWith(pattern.slice(1)) : pattern.endsWith("*") ? name.startsWith(pattern.slice(0, -1)) : name === pattern,
92
+ );
93
+ }
94
+
95
+ /** A working tree (`.git` inside) or a bare repository (`HEAD`, `objects`, `refs`). */
96
+ export function isRepository(directory: string): boolean {
97
+ return (
98
+ existsSync(path.join(directory, ".git")) ||
99
+ (existsSync(path.join(directory, "HEAD")) && existsSync(path.join(directory, "objects")) && existsSync(path.join(directory, "refs")))
100
+ );
101
+ }
102
+
103
+ /** The first repository at or under `directory`, undefined when there is none; throws when it cannot search. */
104
+ function findRepository(directory: string): string | undefined {
105
+ if (isRepository(directory)) return directory;
106
+ const result = spawnSync("find", [directory, "(", "-name", ".git", "-o", "-name", "HEAD", ")", "-print"], { encoding: "utf8", maxBuffer: 64 * 1024 * 1024 });
107
+ if (result.status !== 0) throw new Error(`could not search ${directory} for repositories`);
108
+ for (const found of result.stdout.split("\n").filter(Boolean)) {
109
+ if (path.basename(found) === ".git") return path.dirname(found);
110
+ if (isRepository(path.dirname(found))) return path.dirname(found);
111
+ }
112
+ return undefined;
113
+ }
114
+
115
+ /**
116
+ * Why a directory must be kept because a repository, credentials, or a local
117
+ * database is somewhere inside it; undefined when nothing is. Paths in the
118
+ * reason are relative to `base`.
119
+ */
120
+ export function holdsProtected(directory: string, base: string): string | undefined {
121
+ const protectedFile = spawnSync(
122
+ "find",
123
+ [
124
+ directory,
125
+ "(",
126
+ ...PROTECTED.flatMap((name, index) => [...(index ? ["-o"] : []), "-name", name]),
127
+ ")",
128
+ "!",
129
+ "-name",
130
+ "*.example",
131
+ "!",
132
+ "-name",
133
+ "*.sample",
134
+ "!",
135
+ "-name",
136
+ "*.template",
137
+ // Build systems' own dependency databases are build output, not local data.
138
+ ...BUILD_DATABASES.flatMap(pattern => ["!", "-path", pattern]),
139
+ "-print",
140
+ "-quit",
141
+ ],
142
+ { encoding: "utf8" },
143
+ );
144
+ if (protectedFile.status !== 0) return "could not search for protected files";
145
+ const found = protectedFile.stdout.trim();
146
+ if (found !== "") return `contains ${path.relative(base, found)}`;
147
+ let repository: string | undefined;
148
+ try {
149
+ repository = findRepository(directory);
150
+ } catch {
151
+ return "could not search for repositories";
152
+ }
153
+ if (repository) return `contains repository ${path.relative(base, repository) || "."}`;
154
+ return undefined;
155
+ }
156
+
157
+ /** Why one directory on the way to a candidate, or the candidate itself, rules it out; checked in this order. */
158
+ function componentReason(root: string, current: string, part: string): string | undefined {
159
+ let stats: Stats;
160
+ try {
161
+ stats = lstatSync(current);
162
+ } catch {
163
+ return "missing";
164
+ }
165
+ if (stats.isSymbolicLink()) return "symlink";
166
+ // A nested clone above the candidate owns it (an ignored node_modules that is a repository).
167
+ if (isRepository(current)) return `inside repository ${path.relative(root, current)}`;
168
+ // An ignored `.secrets/build` is still inside credentials.
169
+ if (protectedName(part)) return `inside ${path.relative(root, current)}`;
170
+ return undefined;
171
+ }
172
+
173
+ /** Why a path must not be removed, or undefined when it is safe to. */
174
+ export function unsafeReason(root: string, rel: string): string | undefined {
175
+ if (rel === "" || path.isAbsolute(rel) || rel.split("/").some(part => part === ".." || part === "." || part === ".git")) return "outside the repository";
176
+ let current = root;
177
+ for (const part of rel.split("/")) {
178
+ current = path.join(current, part);
179
+ const reason = componentReason(root, current, part);
180
+ if (reason) return reason;
181
+ }
182
+ const held = holdsProtected(current, root);
183
+ if (held) return held;
184
+ // Checked here, not only at scan time: a file can be force-added between scan and removal.
185
+ // Literal: a path name that looks like pathspec magic (`:(glob)x`) names only itself.
186
+ const tracked = git(root, ["--literal-pathspecs", "ls-files", "-z", "--", rel]);
187
+ if (!tracked.ok) return "could not list tracked files";
188
+ if (tracked.stdout !== "") return "tracked";
189
+ if (!git(root, ["check-ignore", "-q", "--", rel]).ok) return "not ignored";
190
+ return undefined;
191
+ }
192
+
193
+ /** Ignored, untracked, regenerable paths in one repository. */
194
+ export function findCandidates(root: string): Candidate[] {
195
+ const status = git(root, ["status", "--porcelain=v1", "-z", "--ignored=traditional", "--untracked-files=normal"]);
196
+ if (!status.ok) throw new Error("git status failed");
197
+ const found: Candidate[] = [];
198
+ for (const rel of parseIgnored(status.stdout)) {
199
+ const tier = classify(rel, root);
200
+ if (tier) found.push({ path: rel, tier, bytes: 0 });
201
+ const nested = NESTED[path.posix.basename(rel)];
202
+ for (const [child, childTier] of nested ?? []) {
203
+ const childRel = `${rel}/${child}`;
204
+ if (existsSync(path.join(root, childRel))) found.push({ path: childRel, tier: childTier, bytes: 0 });
205
+ }
206
+ }
207
+ return found.filter(candidate => unsafeReason(root, candidate.path) === undefined);
208
+ }
209
+
210
+ /** Kilobyte-accurate sizes from du, which counts each hard link once per call. */
211
+ export function measure(paths: string[]): Map<string, number> {
212
+ const sizes = new Map<string, number>();
213
+ for (let start = 0; start < paths.length; start += 200) {
214
+ const batch = paths.slice(start, start + 200);
215
+ const result = spawnSync("du", ["-sk", "--", ...batch], { encoding: "utf8", maxBuffer: 64 * 1024 * 1024 });
216
+ for (const line of (result.stdout ?? "").split("\n")) {
217
+ const match = /^(\d+)\t(.*)$/.exec(line);
218
+ if (match) sizes.set(match[2]!, Number(match[1]) * 1024);
219
+ }
220
+ }
221
+ return sizes;
222
+ }
223
+
224
+ /** Candidates in the chosen tiers, without paths inside another chosen path. */
225
+ export function selected(candidates: Candidate[], tiers: ReadonlySet<Tier>): Candidate[] {
226
+ const chosen = candidates.filter(candidate => tiers.has(candidate.tier)).toSorted((a, b) => a.path.length - b.path.length);
227
+ return chosen.filter((candidate, index) => !chosen.slice(0, index).some(other => candidate.path.startsWith(`${other.path}/`)));
228
+ }