@a2f0/agent-tool 0.1.83 → 0.1.85

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.
@@ -19,7 +19,7 @@ export type Decision = "allow" | "ask";
19
19
  export interface CatalogEntry { command: string; class: PermissionClass; applyClass?: PermissionClass }
20
20
 
21
21
  export const CATALOG: CatalogEntry[] = [
22
- ...["--help", "--version", "logs", "runs list", "doctor", "config show", "branch check", "branch status", "commits check", "checks binaries", "repo context", "policy check", "toolchain check", "ci gate", "ci timings", "release plan", "release verify", "pr context", "pr checks", "pr logs", "pr preflight", "pr threads list", "versions plan", "versions check", "dependencies check-terraform-plan", "dependencies diff", "skills list", "skills check", "hooks check", "push-gate hook", "push-gate check", "repo base-health", "review carry", "images list", "graph check", "state-machines", "permissions show", "permissions check", "proc list", "perf diff", "screenshots status"]
22
+ ...["--help", "--version", "logs", "runs list", "doctor", "config show", "branch check", "branch status", "commits check", "checks binaries", "repo context", "policy check", "toolchain check", "ci gate", "ci timings", "release plan", "release verify", "pr context", "pr checks", "pr logs", "pr preflight", "pr threads list", "versions plan", "versions check", "dependencies check-terraform-plan", "dependencies diff", "skills list", "skills check", "hooks check", "push-gate hook", "push-gate check", "repo base-health", "review carry", "images list", "graph check", "deslop", "state-machines", "permissions show", "permissions check", "proc list", "perf diff", "screenshots status"]
23
23
  .map(command => ({ command, class: "read" as const })),
24
24
  ...["bun install", "bun update", "bun remove", "bun test", "branch create", "versions bump", "versions prepare", "versions resolve-conflicts", "images build", "screenshots build", "review", "init", "proc stop"]
25
25
  .map(command => ({ command, class: "local" as const })),
@@ -3,6 +3,7 @@ export const BUNDLED_SKILLS: Readonly<Record<string, string>> = {
3
3
  "app-store-readiness": "---\nname: app-store-readiness\ndescription: Audit and prepare iOS, Android, and web apps for release, covering platform interface guidance, accessibility, privacy disclosures, store metadata, and likely review blockers. Use for a readiness assessment or pre-submission preparation, not ordinary feature implementation.\n---\n\n# App Store Readiness\n\nProduce an evidence-backed release decision for the requested platforms.\nTreat store approval, build acceptance, automated accessibility checks, and\nhuman usability as separate outcomes. A successful build or beta upload does\nnot establish readiness.\n\n## Establish the candidate\n\nRead the repository's instructions, release documentation, and readiness\nguide (`docs/readiness.md` when present). Identify the source revision, app\nIDs, version/build, supported devices and OS/browser versions, distribution\ntracks, and the artifact actually tested. Map the user journeys and\napplicable features: accounts, payments, user content, ads/tracking,\nsensitive permissions, children, background work, local storage, and external\nservices. Mark irrelevant checks **N/A** with a reason.\n\nUse the user's scope. A report-only request stays read-only.\nPreparation/dogfooding can include reversible fixes and local tests. This\nskill does not by itself authorize uploads, submission, publication, messages\nto reviewers, changes to pricing or store declarations, or purchases. Existing\nexplicit authorization still applies; do not ask for it again. Do not\nfabricate review contacts, privacy answers, age ratings, or product claims.\n\n## Check the applicable platforms\n\nRead only the references for the requested platforms:\n\n- [iOS / iPadOS](references/ios.md): Apple review risks, HIG,\n accessibility, and submission evidence.\n- [Android](references/android.md): Play policy, Material/Compose\n accessibility, release behavior, and console evidence.\n- [Web](references/web.md): WCAG, browser behavior, privacy/support pages,\n and deployment evidence.\n\nOpen the current official sources linked there. Record the access date and\nthe exact requirement, deadline, exception, and distribution context that\naffect this candidate. Do not reuse remembered target API, SDK, billing, or\nregional payment rules. If a documentation page is only a JavaScript shell,\ntry its official linked documentation or an official text/JSON representation\nbefore relying on it. If a source is inaccessible, mark that decision\nunverified rather than silently assuming it is current. Distinguish mandatory\nstore policies from interface recommendations, chosen accessibility targets,\nand repository conventions. Do not present a guideline preference as certain\nrejection.\n\n## Gather evidence, repair, and retest\n\nTrace important claims from listing/policy → source and dependencies → built\nartifact → runtime behavior. Run the repository's documented readiness lanes\n(`docs/readiness.md`) when present against the candidate for artifact and\nstore-record evidence; their reports leave manual, declaration, and policy\nchecks unverified by design. Inspect\npublic links and actual store configuration when access is available; never\ninfer console completion from local metadata files. Keep credentials,\nreviewer contact details, user records, and private diagnostics out of reports\nand Git. Use local, disposable test data and dedicated devices where\navailable.\n\nExercise launch, the core task, settings, dismissal/back navigation,\nbackground/foreground, and persistence/failure paths. Include a compact\nlayout, large text/zoom, light/dark modes, localization, and relevant\nassistive input. For accessibility, inspect names, roles, states, reading\norder, focus, adjustment actions, contrast, and target sizes. Test the\nshipping configuration, including minification and extensions/widgets where\napplicable. Follow the repository's validation commands; do not invent a\nsubstitute gate.\n\nRecord reproducible failures with platform, device/configuration, affected\njourney, and supporting evidence. Repair actionable issues within scope and\nretest the affected paths. If fixing one finding changes data flows,\npermissions, commerce, or declared capabilities, reconcile the resulting\npolicy/metadata impact. Escalate product decisions only when needed; keep\nunrelated checks moving. Do not add accounts, analytics, permission prompts,\nor generic compliance UI merely to satisfy an inapplicable checklist.\n\n## Prepare the reviewer packet\n\nTreat what the reviewer receives as part of the candidate. Before a first\nsubmission, and whenever the core flow changes, the review notes answer\nwithout being asked:\n\n- the app's purpose and audience, the problem it solves, and why it is worth\n having over established apps in its category;\n- how to reach each main feature from launch, with demo credentials, sample\n files, or a statement that none are needed;\n- each external service the core features rely on (data providers,\n authentication, payments, AI), or a statement that there are none;\n- regional differences in features or content, or confirmation that there are\n none;\n- authorization for regulated services or third-party material, or why it\n does not apply;\n- where to find a screen recording on a physical device running the latest\n OS, starting at launch and covering the typical flow plus any account\n creation, login, and deletion, user-content reporting and blocking, and\n access to paid content.\n\nApple sends exactly this list as a Guideline 2.1 \"Information Needed\" request,\nwhich costs a first submission a full review round trip. Keep the notes under\nversion control when the repository keeps its listing metadata, guard their\ncoverage with a test, and keep recordings outside Git. Never commit demo\ncredentials: enter them in the console's sign-in fields (App Store Connect's\nApp Review Information, Play Console's App access) and have the committed notes\nsay where they are. Check every claim in the\nnotes against the submitted build. A recording or physical-device test the\nagent cannot perform is an owner prerequisite with an exact next action, never\na pass.\n\n## Deliver the readiness record\n\nUse the repository's existing report convention or a concise PR attachment.\nInclude:\n\n- Candidate revision/artifact, audit date, devices, commands, and official\n source links.\n- Per-platform result: **ready within tested scope**, **not ready**, or\n **incomplete**.\n- Findings with severity (blocker / major / minor / advisory), evidence,\n source or design basis, remediation, and retest outcome. Separate fixed\n findings from open ones.\n- A coverage table with **verified**, **failed**, **unverified**, and\n **N/A**. A source-only inspection is not a runtime pass; a simulator is not\n physical-device coverage; an automated scan is not a VoiceOver/TalkBack\n session or complete WCAG conformance.\n- Remaining release prerequisites with owner and an exact next action.\n Unverified submission-critical items prevent a ready verdict. Explain\n inaccessible-console or manual-testing limits without claiming those checks\n passed.\n\nKeep reusable procedure in the skill and dated findings in the report.\nRe-audit changes made after the tested candidate; do not carry evidence across\nunrelated artifacts. When shipping is requested, hand the concrete fixes and\nunresolved release prerequisites to the repository's shipping workflow.\nMerging improvements is distinct from declaring the app ready for public store\nsubmission.\n\n## Ownership\n\nagent-tool (`a2f0/agent-tool`) owns this skill in `skills/app-store-readiness/`.\nRepositories get it from `agent-tool skills install --apply`; do not edit the\ninstalled copy. Change it in agent-tool by PR. A repository's readiness guide,\nlanes, devices, and store records belong in its own docs, such as\n`docs/readiness.md`.\n",
4
4
  "audit-trails": "---\nname: audit-trails\ndescription: Audit application workflows for missing or incomplete audit trails and produce an evidence-backed report or GitHub issue. Use for a requested audit-coverage review, not a general security review or a checklist inspection within the product.\n---\n\n# Audit Trails\n\nTrace consequential application changes from their entrypoints to durable\nhistory and authorized readers. Identify missing events, incomplete attribution,\nmisleading events, and inaccessible history. A timestamp, application log, or\ncurrent-state row alone is not a history of who changed what.\n\nWork from repository code and local tests. Do not read production data or\ncredentials, implement findings, deploy, or ship changes as part of this skill.\nCreate or update a GitHub issue when the user requested one; otherwise return\nthe report without publishing. Honor authorization already given in the session.\n\n## Establish scope\n\nStart [usage tracking](references/usage-receipts.md) now, before audit work or\ndelegation. Save a baseline and run/batch identity beside the private report;\ncheckpoint usage with coverage after each slice and before a pause. A resume\nkeeps the run identity, previous receipts, and publication handle, but starts a\nnew nonoverlapping batch. Missing counters must be disclosed, not estimated.\n\nRead repository guidance and its product and retention documentation. Resolve\nthe repository with `gh repo view --json nameWithOwner`. Record the audited\ncommit, dirty paths, requested focus, and exclusions. Do not claim a committed\nrevision describes uncommitted behavior. Use a clean worktree if dirty files\nwould affect a probe of the committed revision.\n\nRead the repository's own audit notes (its `AGENTS.md` or the docs it points\nto) when present: they may map entrypoints, the shared event store and its\nhelpers, migrations, readers, capability checks, and a local probe harness.\nTreat such a map as a starting point, not a coverage claim. Otherwise discover\nthe entrypoints, event stores, migrations, and readers yourself.\n\nWith no focus, inventory the application and prioritize access changes,\ndestructive actions, financial changes, and externally initiated work. Review\nmanageable slices sequentially; keep a coverage table so partial work is not\nreported as a complete audit. With `resume <report-path>`, verify the recorded\nrepository and revision, reuse its evidence, and continue unchecked paths. If\nthe revision changed, revalidate affected findings before carrying them forward.\n\nKeep reports and scratch probes outside the checkout unless the user requested\na repository artifact. Record the report's absolute path for resuming.\n\n## Trace coverage\n\nInventory write entrypoints: UI/API mutations, authentication hooks, webhooks,\nscheduled jobs, inbound messages, maintenance scripts, and shared helpers used\nby REST or MCP. Read-only sensitive access is a separate requirement; flag it\nonly when repository policy or the requested scope requires an access log.\n\nFor each selected workflow, follow:\n\n1. Actor and organization resolution, authorization, and validation.\n2. The actual persisted mutation and its success, no-op, and failure paths.\n3. Event writes through direct calls, shared helpers, database triggers, or\n provider-specific histories. Read migrations in order, including dropped\n and replacement triggers; when trigger coverage is uncertain, inspect the\n final schema in a scratch database with every migration applied, not one\n built before a later migration. Search results are leads, not proof of\n absence.\n4. Atomicity between the change and its event; conditional writes, stale saves,\n retries, and duplicate webhooks must not produce misleading success events.\n5. Stable action, resource/subject IDs, time, actor snapshot, and minimal useful\n change details. Distinguish the initiating human, API key/channel, and system\n or provider actor. Never recommend fabricating a human for background work.\n6. Authorized retrieval in the workspace feed and relevant record history,\n tenant/capability boundaries, and what remains after deletion or retention.\n\nTreat a separate contract or provider history as existing coverage. Report a\nshared-feed integration gap separately from a missing durable trail. Likewise,\ndocumented purge behavior is not automatically a defect, and historical gaps\ncannot be repaired by inventing actors, timestamps, or old values.\n\nProposed details should use an allowlist. Do not copy secrets, tokens, document\ncontents, screening reports, or unrestricted payloads into events or issues.\nIf a new event would expose restricted data through a broadly readable feed,\ninclude the required reader permission change in the proposal.\n\n## Verify and rank\n\nBefore promoting a finding, trace the write and all plausible event mechanisms.\nUse an existing test or a small synthetic local probe when it can resolve a\nmaterial uncertainty. A useful probe changes a record, inspects durable history,\nand checks rollback, replay, or reader isolation where relevant. Record the\ncommand and result. Do not create tests that merely search for helper names.\n\nLabel evidence **Reproduced** (a local behavior probe or test) or **Traced**\n(a complete source path). Keep unresolved suspicions under **Unverified leads**.\nDo not present absence from a grep result as a verified finding.\n\nRank impact with a concrete explanation: high for changes to access, money,\nor destructive operations that cannot be attributed; medium for ordinary\nbusiness changes or missing shared visibility with another durable trail;\nlow for presentation or convenience gaps. Adjust to actual product behavior.\n\nSearch existing issues before publication. Link matching work and avoid opening\nduplicates. Recheck code before reusing a historical finding.\n\n## Deliver\n\nUse [the report template](references/report-template.md). Each finding needs a\ntrigger, actual and expected behavior, revision-pinned evidence, impact,\nrecommended event/reader behavior, and observable acceptance criteria. Include\nchecked coverage, unverified leads, and explicit limitations.\n\nInclude an **Audit usage receipt** in every report, even for partial work,\nzero findings, or unavailable counters. Follow [usage publication and\nreadback](references/usage-receipts.md#publish-and-resume): the receipt goes in\nthe issue body so findings and accounting publish together. Preserve existing\npublication and security-disclosure authorization; without it, save locally.\nPrefer one ranked report issue unless the user requested separate issues. If a\nmatching issue already covers the audit, update it only when authorized to do\nso; otherwise link it in the report. Never recreate an issue to retry a failed\nreceipt update. Report incomplete publication alongside the saved report.\n\nReturn the issue or report link, the highest-impact gaps, what was actually\nchecked, and remaining scope. Discovery does not imply the gaps were fixed.\n\n## Ownership\n\nagent-tool (`a2f0/agent-tool`) owns this skill in `skills/audit-trails/`.\nRepositories get it from `agent-tool skills install --apply`; do not edit the\ninstalled copy. Change it in agent-tool by PR. Repository-specific audit maps,\nprobe harnesses, and retention rules go in that repository's `AGENTS.md` or the\ndocs it points to.\n",
5
5
  "cross-agent-review": "---\nname: cross-agent-review\ndescription: Review committed branch changes with an independent Antigravity CLI (agy), Claude Code, Codex, or OpenCode reviewer, and repair actionable findings when requested.\n---\n\n# Cross-Agent Review\n\nUse the installed `agent-tool` executable. Read the repository's development and\nreview policy and `agent-tool.json` when present. Keep project validation commands\nand release rules in the repository; do not assume Bun, a workspace layout, or\nparticular CI job names.\n\nSelect an independent reviewer using a different model/provider from the author\nwhen possible, not merely a different CLI: Hermes, OpenCode, and `agy` can use\nthe same model as another harness (`agy` selects a model through\n`review.agyModel`, so it can run a Claude model when authoring with Gemini or a\nGemini model when authoring with Claude). Hermes can coordinate this skill but\nis not a `review` adapter. Honor a requested reviewer or effort; otherwise use\nan available independent reviewer.\nRun `agent-tool doctor` if CLI compatibility is uncertain.\n\nRun noisy validation or repair checks through\n`agent-tool run --label <check> -- <command> [args...]`. Read its bounded failure\ntail and use `agent-tool logs <log>` or a targeted search for more evidence.\nKeep `agent-tool review` direct: it retains reviewer stderr in a private local\nlog and displays the complete final review. Never hide, truncate, or substitute\na command success receipt for findings and the final verdict.\n\nReview committed changes with `agent-tool review agy`, `agent-tool review claude`,\n`agent-tool review codex`, or `agent-tool review opencode`. Optional effort is\n`low`, `medium`, `high`, `xhigh`, or `max`. For a local or non-GitHub repository,\nadd `--base <commit-or-ref>`.\nFor a coordinated GitHub review, pin the fetched base using\n`AGENT_TOOL_REVIEW_BASE_REF`, the base branch name such as `main` (not a\nremote-tracking ref like `origin/main`), and `AGENT_TOOL_REVIEW_BASE_OID`, its\nfetched commit. Fetch from the repository that owns the PR, which can differ\nfrom the checkout's origin.\n\nUse `agent-tool repo context --fetch` to resolve and fetch the PR's own base,\nthen record the exact base and HEAD before reviewing. The tool reviews raw committed\nfiles and excludes worktree edits. A zero exit means a complete review was\nreturned; it does not mean the findings are non-blocking. Read the final\n`VERDICT: BLOCKER|MAJOR|MINOR|SUGGESTION|CLEAN` and the findings. A reviewer\nthat labels findings `[P0]` through `[P3]` uses the same scale: `[P0]` and\n`[P1]` are BLOCKER and MAJOR, `[P2]` and `[P3]` are MINOR and SUGGESTION.\nObservations under `Upstream (agent-tool):` concern files agent-tool generated\nin the repository; they carry no severity and do not block. Report them for\nagent-tool instead of editing those files.\n\nIf a CLI is unavailable, out of credits, or returns an unusable review, try\nanother available reviewer (including `agy`, `claude`, `codex`, or `opencode`,\npicking a different model/provider from the author) and disclose the fallback.\nDo not silently convert a failed review into CLEAN or call an in-session review\nindependent.\n\nFor report-only requests, report findings without changing files or history.\nWhen repairs are authorized, address actionable BLOCKER and MAJOR findings,\nvalidate with the repository's relevant checks, commit the repairs, and review\nthe new HEAD. Continue while meaningful progress is possible; report an impasse\nwhen progress requires a material user decision. A repaired commit is unreviewed\nuntil the next review completes. Preserve unrelated work.\n\nBefore reporting success, confirm HEAD still matches the reviewed commit and\nthat an existing PR points to that same commit. If the base moved, refresh it and\nreview again before shipping, unless the new HEAD only integrated the base and\nprepared versions and `agent-tool review carry <reviewed-head> <new-head>`\naccepts it; then report the review as carried, with both heads. Report\nreviewer, exact base and head IDs, verdict, remaining findings, validation, and\nany repairs performed. This skill does not authorize pushing, opening a PR, or\nmerging unless the user requested that work.\n",
6
+ "deslopify-refactor": "---\nname: deslopify-refactor\ndescription: Behavior-preserving simplification and refactoring to remove agent-written slop, duplication, dead surface area, god-files, unnecessary wrappers, and test-fixture bloat while proving observable behavior is unchanged. Use when asked to de-slopify, simplify, reduce duplication, split oversized modules, prune dead code, or run a simplification sweep across repositories; not for converting boolean flags into state machines (explicit-state-machines), speeding up CI or tests (optimize-ci), page-load optimization (performance-pass), or greenfield contract redesigns.\n---\n\n# De-slopify Refactor\n\nTreat every simplification as a proof obligation: the simpler program must be\nobservably equivalent to the original. Remove real complexity, duplication, dead\ncode, and misleading scaffolding, but never call a change a refactor unless\nbehavior preservation is established.\n\n## Simplification bar\n\nPrefer levers in this order:\n\n1. **Delete**: dead code, unreachable internal branches, unused parameters,\n stale shims, redundant wrappers, and stale task-plan comments.\n2. **Flatten or split**: inline one-off non-architectural indirection, collapse\n unnecessary nesting, and split oversized multi-concern files along acyclic\n seams.\n3. **Extract or unify**: share a helper or factory only when callers represent\n the same concept, lifecycle, and error contract.\n\nNever merge two code paths if the shared helper needs boolean mode flags,\ncaller-specific branches, or unsafe type casts (`as`) to paper over differences.\nNet lines removed is a sanity check, not the goal: a shorter file that is harder\nto trace or couples unrelated domains adds slop instead of removing it.\n\n## Find candidates\n\nStart with `agent-tool deslop` (read-only):\n\n- `agent-tool deslop [path...] [--limit N] [--min-score N] [--include-tests] [--by-dir] [--json]`\n ranks tracked source files in the repository holding the working directory, or\n each named path's repository, by seven signals: duplicated multi-line code\n blocks (`duplicate-block`), structurally identical blocks with renamed\n identifiers/literals (`parametric-clone`), oversized files (`oversized-file`),\n long functions (`long-function`), lint/type suppression clusters\n (`suppressions`), exported pass-through wrapper cascades (`thin-wrapper`), and\n single-caller micro-files or non-index re-export shims (`micro-file`).\n- Run `agent-tool deslop --by-dir --include-tests` first on any large repository\n or monorepo to see directory-level duplication hotspots, test-to-source ratios,\n and micro-file clusters before choosing slices.\n- Pass `--include-tests` as a first-class phase, not an afterthought: test\n helpers, copy-pasted fixtures, and overlapping test files are often the\n largest, lowest-production-risk simplification targets in agent-built codebases.\n- If the repository's pinned agent-tool lacks the command or flags, run\n `bunx --bun @a2f0/agent-tool@latest deslop`.\n\nThe scanner finds leads, not verdicts. Pair it with the repository's existing\nstatic tools before reading by hand:\n\n- Dead exports, files, and dependencies (`knip`, `ts-prune`, compiler unused\n checks).\n- Import cycles and layer leaks (`agent-tool graph check`, `dependency-cruiser`).\n- File-size, complexity, and suppression baselines when the repository keeps one.\n\nRead [references/pathology-catalog.md](references/pathology-catalog.md) for\ncommon simplification opportunities, scoring, and false-positive traps, and\n[references/lessons.md](references/lessons.md) for cross-repository lessons from\nearlier passes.\n\n## Decide what to simplify\n\nSimplify a candidate only when all three hold:\n\n1. It removes real complexity, duplication, dead surface area, or misleading\n scaffolding under the simplification bar above.\n2. Its equivalence boundary is explicit before editing.\n3. Verification can prove observable behavior is unchanged (or pre-existing\n failures are unchanged).\n\nLeave a candidate alone when:\n\n- Similarity is accidental: helpers share shape but differ in rounding,\n thresholds, sort order near hashes, error-prefix classification, or key arity.\n- The wrapper is an enforced architectural boundary (such as a route -> service\n -> workflow facade) or a public API contract.\n- A defensive guard, `ref` mirror, memoized identity, or lint/type idiom (such\n as `Reflect.get` under `noPropertyAccessFromIndexSignature` + `useLiteralKeys`)\n prevents a real bug or satisfies a repository rule.\n- Equivalence cannot be proved at reasonable cost.\n\nSee [references/pathology-catalog.md#leave-alone-and-common-traps](references/pathology-catalog.md#leave-alone-and-common-traps)\nbefore touching hash-adjacent code, error classifiers, React hooks, or\nserialization paths. Record each non-obvious candidate you leave alone and why\nin the PR body (or inline comment when the trap is subtle) so future passes do\nnot re-propose it.\n\n## Execute and prove equivalence\n\n1. **Establish the baseline**: inspect `git status`, read the repository's\n `AGENTS.md` and scripts, and run the narrowest credible baseline (targeted\n tests, typecheck, lint, graph/architecture checks). Do not edit before you\n have a baseline or a documented reason one is unavailable.\n2. **State the equivalence claim before editing**: in a few lines, name the\n surface, what must stay unchanged (inputs/outputs, public exports, error\n classes/messages/status codes, side effects and ordering, async/resource/React\n lifecycle, serialization, security boundaries), and how you will verify it.\n3. **Edit one lever at a time**: keep changes local and mechanical. Do not mix\n simplifications with drive-by formatting, unrelated renames, or dependency\n upgrades.\n4. **Prove characterization tests against `<base>`**: when existing tests do not\n cover risky behavior, add characterization tests first and run them against\n the pre-refactor file (`git show <base>:<file>` in a temporary copy, or before\n the refactor edit) to prove they lock in the original behavior rather than\n circularly testing the new code.\n5. **Split discovered bugs and divergences**: close reading often surfaces real\n latent bugs (swallowed errors, unmapped status codes, stale closures) or\n accidental behavioral drift between duplicated paths. Do not smuggle a\n behavior change into a `refactor/` PR:\n - Ship a clear bug fix as its own `fix/` PR with a regression test proven to\n fail before the fix.\n - Defer an ambiguous behavioral divergence and note it in the PR body or\n tracking issue for an explicit decision.\n6. **Verify after editing**: re-run the baseline checks plus targeted checks for\n the touched surface. Confirm no unexpected build-output, schema, snapshot, or\n warning changes appeared. Rebuild workspace packages (such as a client SDK's\n `dist`) before trusting downstream tests. If behavior changed unintentionally,\n revert the candidate.\n\n## Test-suite and fixture consolidation phase\n\nTreat `--include-tests` as a first-class simplification phase whenever a\nrepository has heavy test volume, high test-to-source ratios in `--by-dir`, or\nlarge `test/helpers` directories:\n\n1. Survey test hotspots with `agent-tool deslop --by-dir --include-tests --json`.\n2. Target three high-yield, low-production-risk levers:\n - **Shared builders and harness factories**: replace repeated multi-line\n setup blocks across sibling test files (`duplicate-block` and\n `parametric-clone`) with focused, explicit fixture builders.\n - **Test-helper deduplication**: collapse parallel helper modules that build\n the same domain graph with minor parameter differences.\n - **Redundant case consolidation**: merge or delete demonstrably duplicate\n test cases that exercise the exact same path and assertions without adding\n unique coverage. Never drop security refusals, race/concurrency checks,\n boundary-value cases, or dialect/adapter integration tests.\n3. Prove coverage parity: run the affected test suite before and after, verify\n the same edge cases and failure modes remain guarded, and ship cohesive test\n cleanup slices through `ship-pr`.\n\n## Campaign and multi-wave mode\n\nKeep individual PRs reviewable (roughly 600–1,200 changed lines or one cohesive\nmodule/theme per PR), because mega-PRs hide subtle lifecycle and closure\nregressions. When asked to materially shrink a large repository or monorepo,\nincrease **wave throughput** rather than PR size:\n\n1. **Rank the full backlog first**: run `agent-tool deslop --by-dir --include-tests --json`\n alongside dead-code (`knip`) and architecture checks, and group leads into\n disjoint directory or lens slices (test helpers, high-ratio test directories,\n sibling parametric clones, over-fragmented micro-files, dead surface area).\n Order slices by `estimated net LOC removed x safety`.\n2. **Partition disjoint slices per wave**: assign non-overlapping directories or\n modules to parallel workers (or run consecutive waves in one session) so\n branches do not conflict and each PR stays cohesive and fast to review.\n3. **Ship every slice independently**: each slice gets its own baseline,\n equivalence claim, verification, independent `cross-agent-review`, and\n `ship-pr` merge. Do not stop after one tiny slice when the user requested a\n broad reduction — continue through planned waves until the target scope or\n high-yield backlog is exhausted.\n4. **Track cumulative progress**: keep per-PR accepted/deferred records in each\n PR body and record remaining campaign slices in a tracking issue (when\n authorized) or summary report. Do not commit a running ledger file into the\n repository.\n\n## Ship and self-improve\n\n- Work on a `refactor/<topic>` branch (`fix/<topic>` for split bug fixes) and\n ship with [ship-pr](../ship-pr/SKILL.md), including independent\n [cross-agent-review](../cross-agent-review/SKILL.md). Independent review\n catches subtle lifecycle, closure, and contract regressions that tests miss.\n- Keep PRs reviewable: target roughly 600–1,200 changed lines or one cohesive\n module or theme per PR rather than sweeping an entire package in one giant\n diff. Use multi-wave campaigns for larger reductions.\n- Do not commit a running ledger file (such as `.codex/deslopify-ledger.md`)\n into the repository. Put the pass record directly in the PR body:\n - Accepted simplifications (lever, equivalence claim, files, verification, net\n LOC delta).\n - Candidates inspected and left alone or deferred, with reasons.\n - For multi-PR campaigns, track the remaining backlog in a GitHub issue via\n [open-issue](../open-issue/SKILL.md) (when explicitly requested) or in the\n campaign summary report.\n- **Make the skill self-improving**:\n - When a pass uncovers a repository-specific idiom, trap, or file-budget\n constraint, record it in that repository's `AGENTS.md` or an inline comment\n beside the code.\n - When a pass learns a cross-repository trap, false positive, or scanner gap,\n send a PR to `a2f0/agent-tool` updating\n [references/lessons.md](references/lessons.md),\n [references/pathology-catalog.md](references/pathology-catalog.md), or the\n `agent-tool deslop` scanner and its tests.\n\n## Across many repositories\n\nA sweep across repositories follows the coordinating workspace's sweep rules\n(status, sweep ledger, one delegate per repository, `ship-pr` each). Run\n`agent-tool deslop --json` (or `bun run deslop --json` in a matrix workspace)\nfirst and attach each repository's leads to its delegate brief. For a large\nmonorepo package, run parallel read-only surveys by lens (dead code,\nduplication, oversized files, wrappers/scaffolding, test slop), then assign\ndisjoint directory slices with centralized verification. Repositories with no\nworthwhile candidates close as `unchanged` quickly; record what was checked.\n\n## Ownership\n\nagent-tool (`a2f0/agent-tool`) owns this skill in `skills/deslopify-refactor/`\nand the `deslop` scanner with its tests in `src/deslop/`. Repositories get it\nfrom `agent-tool skills install --apply`; do not edit the installed copy.\nChange it in `a2f0/agent-tool` by PR, and fold cross-repository lessons into\n[references/lessons.md](references/lessons.md) and the scanner there.\n",
6
7
  "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
8
  "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
9
  "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",
@@ -29,6 +30,11 @@ export const BUNDLED_SKILL_REFERENCES: Readonly<Record<string, Readonly<Record<s
29
30
  "references/usage-receipts.md": "# Audit usage receipts\n\nThis procedure applies to any repository audited with audit-trails. It measures\nthe audit workflow, not the instruction file's size. Use the\n[report template](report-template.md#audit-usage-receipt) even when all usage is\nunavailable. It does not authorize an audit, model call, issue, or disclosure.\n\n## Start and checkpoint\n\nBefore work or delegation, create a private checkpoint beside the local report\n(outside the checkout by default). Use a fresh opaque run ID, such as a UUID,\nnot a provider session ID. Record:\n\n- Run ID and batch ID, start time, full/batch/resumed scope and requested focus.\n- Audited repository and full commit, dirty-path treatment, the audit-trails\n version (the `agentToolVersion` in `.agent-tool-skills.json`) or hashes of\n the loaded skill and references, harness name/version, provider/model and\n effort when exposed; mark missing metadata unavailable.\n- Usage source and its documented semantics, dedicated run identity or the\n before counters and last completed request boundary. Keep raw identities,\n source paths and evidence private; publish only sanitized provenance/digests.\n- Expected coordinator, children, auxiliary model calls and terminal-launched\n CLI auditors, with each source's inclusion in parent totals (or unknown).\n- Report path, canonical issue URL if already published, receipt run marker,\n last verified body and pending update. Do not discard these on interruption.\n\nPrefer dedicated run counters. In a mixed session take before/after snapshots;\nif isolation is impossible, say shared-session usage is not attributable to the\naudit. A missing baseline cannot be retroactively invented. At each coverage\ncheckpoint and before stopping, save available counters, measured cutoff,\ncompleted/partial/interrupted status, and remaining scope.\n\nResume the same run with a new batch ID and baseline. Keep prior batches; record\nrevision, harness, or model changes and revalidate affected findings. Deltas\nmust have disjoint request boundaries. Never add cumulative snapshots from\nmultiple resumes as if they were separate runs. Counter resets or changed\nsemantics require separate rows, not negative deltas or silent correction.\n\n## Evidence and accounting\n\nUse actual harness/provider-reported input/output tokens, cache-read/cache-write,\nreasoning, API-call counts, and duration when exposed. Keep native field names\nand semantics in the evidence; distinguish wall-clock elapsed time from a\nprovider's duration. Missing/null fields mean unavailable, not zero. Even a\nnumeric zero is not proof of measurement if that harness defaults missing\nprovider usage to zero; disclose that source limitation.\n\nDo not infer runtime consumption from skill bytes, context size estimates,\nmodel guesses, agent-tool command duration/log bytes, or a subscription meter.\nStatic load size, if useful, belongs in a separately labeled estimate, never\nin the usage total. Optional dollar estimates are neither subscription charges\nnor quota usage.\n\nFor the installed harness, verify its help and source/schema before naming a\ncollector. Do not guess Claude/Codex transcript paths or counter fields; if no\nverified source is exposed, publish `unavailable (no verified usage source)`.\nNo new accounting CLI is required by this skill. A demand for exact counters\nthat the harness does not expose is a tooling blocker, not permission to\ninvent numbers or build a per-repository runtime collector.\n\n### Verified Hermes source\n\nAn outer launcher can use `hermes -z \"$task\" --usage-file \"$usage_file\"` for an\nalready authorized child run; the file is written after the run returns, not\nwhile its final request is still running. Check the installed\n`hermes_cli/oneshot.py` writer and [CLI reference][hermes] for the actual\nversion. The fields below were checked against [Hermes\nv0.22.5+2418.g8209674][hermes-source]; verify them again after upgrades.\nOne-shot mode bypasses approval prompts: do not switch a live audit\nto it or launch another audit merely to obtain usage. Its execution policy\nneeds separate authorization.\n\nThe writer copies `input_tokens`, `output_tokens`, `cache_read_tokens`,\n`cache_write_tokens`, `reasoning_tokens`, `total_tokens`, `api_calls`, `model`,\n`provider`, `session_id`, `completed`, `partial`, `interrupted`, and\n`turn_exit_reason`. Keep session IDs and free-text failure details private.\nWhen present, `auxiliary.by_task` breaks down auxiliary calls, and\n`total_including_auxiliary` includes them already: never add it to main or\nauxiliary totals. Those fields alone do not establish child coverage, per-model\nbreakdowns, effort, or duration; mark unexposed dimensions unavailable.\n\n### Combine only proven nonoverlapping coverage\n\n- Keep coordinator, delegated children, auxiliary calls, and external CLI\n auditors identifiable. External CLI auditors need their own receipts; a\n terminal invocation's elapsed time is not their token usage.\n- Deduplicate repeated assistant events by provider request identity. Keep raw\n IDs private. For cumulative sources use differences, not sums of snapshots.\n- Do not add child usage already rolled into the parent. When inclusion is\n unknown, show separate non-additive rows and explain why no total is valid.\n- Cache and reasoning may be subfields of input/output. Do not add them to\n totals without verified provider semantics. Preserve native totals rather\n than imposing an incompatible token formula.\n- Group by provider/model when switched; if the source only labels the final\n model, call its aggregate mixed/unattributed instead of assigning it all to\n that model. Sum batches only with matching semantics and disjoint coverage.\n- Partial measurements are measurable subtotals, never a workflow grand total.\n Name every missing participant/field and exclude it explicitly.\n\n## Cutoff, not an imaginary final bill\n\nA live coordinator cannot see its own post-exit receipt. Freeze the receipt at\nthe last completed provider request **before publication** and label that\ncutoff and timestamp. Exclude the in-flight request, publication work and final\nreply, plus anything else not observable. Save what is available at checkpoints\nso an interrupted audit can still report partial usage.\n\nAlternatively, an authorized outer launcher can reconcile the same receipt\nafter the audited child exits. Include the child's observable tail, but keep\nunmeasured launcher/publication costs excluded. Never recursively invoke the\naudit to produce a receipt or promise an exact final bill inside that run.\n\n## Publish and resume\n\nPublish the receipt **in the report body**. This avoids a second comment write\nand a race with bot comments; there is no receipt comment ID. Partial audits,\nzero findings, and unavailable counts still need the section. Retain the existing\nissue-publication and security-disclosure gates. Without authorization, save\nthe report and receipt locally, and report that publication was not authorized.\nAllowlist only sanitized run/batch IDs, repository/revision, versions/hashes,\nmodel/provider/effort, counters, timestamps, outcome and coverage descriptions.\nNo secrets, credentials, raw prompts/transcripts, request payloads, production\nrows, private paths/hostnames, raw session/request IDs or free-text failures.\nReview the entire public body, not just the receipt, before sending.\n\nThe examples require GitHub CLI, jq, and a POSIX shell.\nSet `repo` to the resolved repository, `title` to the report title, `body_file`\nto the private sanitized complete report, and `receipt_dir` to its private\ncheckpoint directory. Run snippets with `sh -eu` (or equivalent fail-fast\nhandling). They are alternatives/steps, not one script to run indiscriminately.\n\nOnly for a new authorized report with no previously created issue:\n\n```sh\ngh issue create --repo \"$repo\" --title \"$title\" --body-file \"$body_file\" \\\n > \"$receipt_dir/issue-url.txt\"\nIFS= read -r issue_url < \"$receipt_dir/issue-url.txt\"\n```\n\nImmediately save the returned URL as `issue_url` in the checkpoint, before any\nlater action. For a resumed/existing report use its recorded canonical URL.\nRead back that exact issue after creation and after every edit:\n\n```sh\ngh issue view \"$issue_url\" --repo \"$repo\" --json url,number,body \\\n > \"$receipt_dir/issue-candidate.json\"\njq -e --arg url \"$issue_url\" --rawfile expected \"$body_file\" \\\n '.url == $url and .body == $expected' \"$receipt_dir/issue-candidate.json\" > /dev/null\nmv \"$receipt_dir/issue-candidate.json\" \"$receipt_dir/issue-readback.json\"\n```\n\nInspect the returned canonical URL/repository/number and compare the decoded\n`body` exactly with the intended complete body, including both run markers and\nthe receipt. A successful write command alone is not verified publication.\nThe snippets compare the URL and decoded body, and only then promote the\ncandidate to the last-verified checkpoint. A failed read or mismatch leaves\nprevious verified evidence intact. Keep one publisher per private directory.\nRecord the canonical URL plus `audit-usage:RUN_ID` as the receipt handle; location\nis the issue body, comment URL/ID not applicable.\n\nFor an authorized resume/retry, read the latest issue body first, replace only\nthat run's `<!-- audit-usage:RUN_ID:begin -->` through matching end marker,\nand preserve other runs and unrelated edits. If absent, append that run's\nsection once; ambiguous or duplicate markers require manual reconciliation,\nnot an overwrite. Serialize publishers for the same issue, recheck the latest\nbody before writing, and reconcile concurrent changes instead of blindly\nsending a stale local body. Do not overwrite another run's receipt. Save the\nreconciled full body privately, then edit the existing issue and read back:\n\n```sh\ngh issue edit \"$issue_url\" --repo \"$repo\" --body-file \"$body_file\"\ngh issue view \"$issue_url\" --repo \"$repo\" --json url,number,body \\\n > \"$receipt_dir/issue-candidate.json\"\njq -e --arg url \"$issue_url\" --rawfile expected \"$body_file\" \\\n '.url == $url and .body == $expected' \"$receipt_dir/issue-candidate.json\" > /dev/null\nmv \"$receipt_dir/issue-candidate.json\" \"$receipt_dir/issue-readback.json\"\n```\n\nOn any failed/ambiguous write or readback, retain the intended body, run marker,\nknown URL and last verified state locally; report **incomplete publication**.\nRecover an uncertain create by finding the existing issue and checking its\nexact run marker before retrying; never blindly rerun create. A failed receipt\nupdate must not create another report issue. If an older report used a receipt\ncomment, retain its recorded comment ID/URL and reconcile that exact receipt\nbefore changing placement; never use `--edit-last` to guess ownership.\n\nSources: GitHub CLI [create][create], [edit][edit], and [view][view]. The shell\nexamples are exercised with a stub CLI in agent-tool's tests\n(`src/skills/auditTrails.test.ts`); they do not open real issues or execute\naudits.\n\n[hermes]: https://hermes-agent.nousresearch.com/docs/reference/cli-commands\n[hermes-source]: https://github.com/NousResearch/hermes-agent/blob/820967473d4d5b6777d3a9419def4be422711d16/hermes_cli/oneshot.py\n[create]: https://cli.github.com/manual/gh_issue_create\n[edit]: https://cli.github.com/manual/gh_issue_edit\n[view]: https://cli.github.com/manual/gh_issue_view\n",
30
31
  "agents/openai.yaml": "interface:\n display_name: \"Audit Trails\"\n short_description: \"Find missing audit trails and report verified gaps\"\n default_prompt: \"Use $audit-trails to review this app's audit coverage and report verified gaps.\"\n"
31
32
  },
33
+ "deslopify-refactor": {
34
+ "references/lessons.md": "# De-slopify Lessons\n\nCross-repository lessons from de-slopify passes, newest first. Add a lesson by\nPR to `a2f0/agent-tool` when a pass discovers a trap, false positive, or scanner\nimprovement that future repositories need; keep repository-specific conventions\nin that repository's `AGENTS.md`.\n\n## Scale reduction with multi-wave campaigns and test-suite consolidation, not mega-PRs\n\nIn `tearleads`, keeping single PRs focused avoided regressions, but stopping\nafter one or two ~100-line source tweaks could not outrun feature growth in a\n1.5M-line monorepo where nearly half the code lived in tests and `test/helpers`\nand exact-line scanning missed parametric sibling clones. Separate PR size from\ncampaign throughput: survey with `agent-tool deslop --by-dir --include-tests`,\ntreat test-fixture consolidation as a first-class phase, and run multi-wave\ncampaigns over disjoint slices so each PR stays reviewable while cumulative\nreductions scale.\n\n## Skip multi-line import blocks when scanning for clones\n\nSingle-line `import` filters miss the inner identifier lines of multi-line\n`import { ... } from ...` statements, creating noisy clone matches across\nunrelated modules. `agent-tool deslop` skips complete multi-line import and\nre-export blocks before computing both exact and parametric clone windows.\n\n## Do not commit a running ledger into the target repository\n\nEarly passes in `tearleads` maintained `.codex/deslopify-ledger.md` inside the\nrepository. It grew to 918 lines of stale history, logged only accepted changes\n(zero rejected or deferred entries), conflicted across parallel PRs, and was\nlater deleted in a docs cleanup. Keep per-PR accepted/deferred records in the PR\nbody and multi-PR backlogs in a GitHub issue instead.\n\n## Small focused PRs beat mega-PRs\n\nSplitting `tearleads` `packages/client-sdk` one module or lever per PR (20\nfile-split PRs, each cleanly reviewed) landed smoothly, whereas a 258-file\npackage-wide `packages/app` PR hid two infinite-render loops and two Major\nclosure/scoping regressions until independent cross-agent review caught them.\nAim for one theme or module (~600–1,200 lines) per PR.\n\n## Independent review catches subtle lifecycle and closure regressions\n\nAutomated tests passed on both `withOverrides` closing over creation-time state\nand billing loads that added `source` to effect dependencies without keying\nstored state by `source`, and on a call-site wrapper that used object spread and\ndropped prototype methods. Independent cross-agent review caught all three. Never\nskip cross-agent review on \"pure\" refactors.\n\n## Check error classifiers and hash comparators before unifying look-alike helpers\n\nIn `tearleads`, two `uniqueSortedStrings` helpers differed only in codepoint sort\nvs `localeCompare`—unifying them would have changed committed manifest hashes.\nSimilarly, `collectContainerKeks` looked identical to the document-sync variant,\nbut its error-message prefix drove the upload stale-KEK retry classifier. Always\ntrace callers of error text and sort outputs before deduplicating.\n\n## Watch build caches and git-tracked linters during file moves and splits\n\nIn monorepos, downstream packages often resolve sibling packages from built\n`dist/` output: rebuild the edited package before trusting downstream tests.\nWhen deleting or moving files, stage deletions before running linters that walk\n`git ls-files`, and remember that `export { foo } from \"./bar\"` does not bring\n`foo` into local scope of the re-exporting module.\n\n## Keep the scanner focused on structural leads\n\nGenerated files (`// Generated by ...`, `@generated`), vendored code, and\ncomment/string literals that merely mention suppression tokens (such as\n`\"eslint-disable\"` inside a linter or scanner) produce noise if scanned naively.\n`agent-tool deslop` skips generated headers and counts suppressions only in\ncomments or attributes; add new noisy patterns to `src/deslop/` when sweeps hit\nthem.\n",
35
+ "references/pathology-catalog.md": "# Pathology Catalog\n\nUse this catalog to identify high-value simplifications, score candidates, and\navoid false positives that introduce regressions.\n\n## High-Confidence Candidates\n\n| Pathology | Typical signal | Safe simplification |\n| --- | --- | --- |\n| Dead code and unreachable branches | Unused exports/files (`knip`), private branch unreachable by types and callers, dead SSR guards in browser-only code | Delete after verifying dynamic imports, routes, config, build scripts, reflection, and deployment entry points |\n| Exact copy-paste blocks | Identical multi-line logic across files (`duplicate-block`) with matching inputs, error semantics, and side effects | Extract one shared helper once evaluation order, comparator semantics, and error messages match |\n| Parametric and structural clones | Structurally identical blocks with renamed identifiers or literals (`parametric-clone`) across sibling modules, handlers, or tests | Extract a thin typed helper or data-driven spec where domain differences stay explicit parameters; never add mode flags to paper over divergence |\n| Over-fragmented micro-files | Tiny production modules (`micro-file`) with only 1 relative JS/TS importer or non-index re-export shims adding import/file-count overhead without enforcing a layer boundary | Verify non-relative callers first (path aliases, workspace package imports, non-JS importers, generated/oversized files are outside the relative-import scan), then fold back into the sole caller or delete the re-export shim while respecting public exports, dependency-graph rules, and file-size budgets |\n| Oversized multi-concern files | God-files (`oversized-file`, `long-function`) mixing validation, mapping, persistence, and orchestration | Split along acyclic seams: map call graph, home shared types to avoid cycles, keep public re-exports stable (and import locally if the parent still calls them), or use `Pick<Interface, ...>` part-objects for large object literals while keeping self-referencing methods in the parent |\n| Non-architectural thin wrappers | Pass-through functions (`thin-wrapper`) adding no logging, metrics, error wrapping, binding, or layer boundary | Inline or remove after checking public imports, exports maps, and dependency-graph layer rules |\n| Duplicate constants and config | Same literals repeated for one domain concept | Centralize when load order, tree shaking, environment overrides, and serialization stay identical |\n| Test-fixture and harness slop | High test-to-source directories (`deslop --by-dir --include-tests`), copy-pasted fixture builders (`duplicate-block` / `parametric-clone`), overlapping test cases, or production fallback branches kept solely for test harnesses missing a provider | Extract focused shared test builders, collapse redundant helper modules and duplicate assertions while keeping every unique edge/security test, and fix test harnesses to provide required context explicitly |\n| Stale task-plan comments and shims | Comments narrating past AI steps or obsolete compatibility aliases no longer referenced | Delete stale narration and dead shims while preserving rationale comments explaining non-obvious invariants |\n\n## Medium-Risk Candidates\n\n| Pathology | Risk | Guardrail |\n| --- | --- | --- |\n| Over-defensive branches | \"Impossible\" inputs may belong to a public or wire contract | Remove only in internal code or after proving every caller and documented contract excludes the case |\n| Over-parameterized helpers | Optional knobs may serve hidden callers, tests, or generated code | Collapse only after auditing all callers, configs, tests, and external API boundaries |\n| Blanket `try/catch` and string error matching | Catch blocks may normalize errors, metrics, retries, or cleanup; string classifiers may drive HTTP status or retry paths | Preserve thrown classes, messages, and side effects exactly; if a blanket catch hides real bugs (e.g., mapping every failure to 409), split the fix into a `fix/` PR |\n| Parallel `v1`/`v2` or legacy files | Old-looking entry point may still be wired in CI, manifests, or deployment config | Verify imports, routes, package exports, build configs, and deployment manifests before deleting |\n| Shallow happy-path tests | Existing suite passes even when edge behavior changes | Add characterization tests and prove them against `<base>` before simplifying |\n\n## High-Risk Boundaries\n\nAvoid simplifying these unless characterization coverage is strong and the\npayoff clearly justifies the risk:\n\n- Auth, authorization, permission checks, session handling, and secret handling\n- Input validation, escaping, sanitization, and file/network/path boundaries\n- Crypto, hashing, canonical ordering, signatures, tokens, and random IDs\n- Transactions, savepoints, migrations, locking, concurrency, retries, and idempotency\n- Async cancellation, streams, subscriptions, and resource cleanup lifecycles\n- React hook order, effect dependencies, memoized identity, and controlled state\n- External serialization formats, wire protocols, caches, databases, and snapshots\n\n## Leave Alone and Common Traps\n\nSkip these—each looks like slop on the surface but causes real regressions when\nmerged or removed naively:\n\n- **Canonical ordering and hash traps**: two `uniqueSortedStrings` helpers where\n one sorts by codepoint (`<` / `>`) for a manifest or content hash and another\n uses `localeCompare`. Unifying them onto `localeCompare` silently changes\n committed hashes.\n- **Error-message and prefix classifiers**: two nearly identical helpers whose\n thrown error text feeds a downstream retry or HTTP-status classifier (for\n example, matching an error prefix to trigger stale-key retry). Changing the\n message silently breaks recovery.\n- **React identity and render-loop traps**:\n - Removing a `useRef` mirror (`setCallbackRef`) when callers pass unstable\n inline setters triggers infinite render loops.\n - Moving a comparator or default object inside a hook/render body when\n downstream effects key on it re-fires registration every render.\n - Adding a runtime/source handle to effect dependencies without also scoping\n stored state by that handle still serves stale in-flight state across\n switches.\n - Factory/override helpers that close over creation-time state instead of\n reading from the current receiver serve stale values.\n- **Enforced architectural layers**: pass-through services (`route -> service ->\n workflow`) look like thin wrapper cascades but exist to satisfy dependency\n direction rules. Check architecture config before flattening.\n- **Type-system and linter idioms**:\n - Hand-rolled `Reflect.get(record, \"key\")` helpers exist where\n `noPropertyAccessFromIndexSignature` collides with `useLiteralKeys`.\n - Generic `Object.fromEntries` builders often force `as` casts that fail\n production type-assertion bans; per-type literals or callbacks stay type-safe.\n - Under `exactOptionalPropertyTypes`, forwarding `{ prop: input.prop }` is not\n equivalent to omitting `prop` when `undefined`.\n - Spreading a class instance (`{ ...instance }`) silently drops prototype\n methods and getters.\n - Extracting helper files into a directory at its `ls-lint` file-count cap\n fails lint; check directory budgets first.\n- **Accidental resemblance**: helpers with different rounding or truncation\n thresholds (`formatByteLength` vs `formatByteSize`, `compactId` vs\n `compactFingerprint`), or structurally similar keys with different arity (a\n 4-part local sort key vs a 3-part deduplication key).\n- **Implicit state machines disguised as flag clutter**: when a file has tangled\n lifecycle booleans or scattered status writes, handle it with\n [explicit-state-machines](../../explicit-state-machines/SKILL.md) rather than\n ad-hoc boolean folding.\n\n## Candidate Scoring\n\nScore leads before editing to pick order:\n\n```text\nvalue: 1 low, 2 medium, 3 high (real complexity/duplication removed)\nconfidence: 1 weak, 2 plausible, 3 proven\nrisk: 1 low, 2 medium, 3 high\n\ntake first: value + confidence >= 5 and risk <= 2\ndefer: confidence < 2 or risk == 3\nreject: value == 1 and risk >= 2, or requires flags/casts to unify\n```\n\nScoring is a forcing function, not a substitute for judgment: a small, obvious\ndeletion with airtight proof is worth taking; a large deletion with unclear\ncontract boundaries should be deferred or rejected.\n",
36
+ "agents/openai.yaml": "interface:\n display_name: \"De-slopify Refactor\"\n short_description: \"Behavior-preserving simplification and slop removal\"\n default_prompt: \"Use $deslopify-refactor to simplify this codebase while proving observable behavior is unchanged.\"\n"
37
+ },
32
38
  "explicit-state-machines": {
33
39
  "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",
34
40
  "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"