@a2f0/agent-tool 0.1.86 → 0.1.87
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/package.json +1 -1
- package/skills/ship-pr/SKILL.md +4 -1
- package/src/skills/bundled.ts +1 -1
- package/src/workflows/checks.ts +54 -6
- package/src/workflows/config.ts +21 -1
- package/src/workflows/pushGate.ts +29 -9
package/package.json
CHANGED
package/skills/ship-pr/SKILL.md
CHANGED
|
@@ -76,7 +76,10 @@ command, so they can be found and stopped.
|
|
|
76
76
|
still runs on the new HEAD.
|
|
77
77
|
4. Run `agent-tool branch push <reviewed-head> --remote <remote>` through
|
|
78
78
|
normal hooks; it verifies local and remote identity afterward. If a hook
|
|
79
|
-
changed content or HEAD, review that result.
|
|
79
|
+
changed content or HEAD, review that result. When the `binaries` guard
|
|
80
|
+
refuses a file, stop and ask the user: `binaries.allow` holds the paths
|
|
81
|
+
the user chose, so add one only when the user names it, and ship that
|
|
82
|
+
addition in its own PR before the files it allows.
|
|
80
83
|
Open the PR using the open-pr skill, or update the existing PR as needed.
|
|
81
84
|
5. Allow configured review bots time to respond, then use
|
|
82
85
|
`agent-tool pr threads list` to fetch review threads and all comments. Follow repository policy for feedback: fix valid findings,
|
package/src/skills/bundled.ts
CHANGED
|
@@ -11,7 +11,7 @@ export const BUNDLED_SKILLS: Readonly<Record<string, string>> = {
|
|
|
11
11
|
"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",
|
|
12
12
|
"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",
|
|
13
13
|
"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",
|
|
14
|
-
"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",
|
|
14
|
+
"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. When the `binaries` guard\n refuses a file, stop and ask the user: `binaries.allow` holds the paths\n the user chose, so add one only when the user names it, and ship that\n addition in its own PR before the files it allows.\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",
|
|
15
15
|
"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",
|
|
16
16
|
"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",
|
|
17
17
|
"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",
|
package/src/workflows/checks.ts
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { readFileSync } from "node:fs";
|
|
2
2
|
import { execFileSync, spawnSync } from "node:child_process";
|
|
3
3
|
import { loadConfig, type AgentToolConfig } from "../config";
|
|
4
|
+
import { validateBinaryAllow } from "./config";
|
|
4
5
|
import { validateCommitSubject } from "../pr/validateCommitSubject";
|
|
5
6
|
import { stripPrNumberSuffix } from "../pr/prNumberSuffix";
|
|
6
7
|
import { assert, git, option, flag, output } from "./core";
|
|
@@ -72,6 +73,47 @@ export function binaryPaths(source: string): string[] {
|
|
|
72
73
|
return result;
|
|
73
74
|
}
|
|
74
75
|
|
|
76
|
+
/** Where `checks binaries` and the push gate's guard read the allowlist from, and what it allows. */
|
|
77
|
+
export interface BinaryPolicy { from: string | null; allow: string[]; error?: string }
|
|
78
|
+
|
|
79
|
+
export const BINARY_HINT = "binaries.allow is read from agent-tool.json at policy.from: the commit a range or push starts from, or HEAD for --staged and --all, never from the files being checked. Its paths are the repository owner's decision: ask before adding one, and land the addition in its own change before the files it allows.";
|
|
80
|
+
|
|
81
|
+
export const commitExists = (ref: string) => spawnSync("git", ["rev-parse", "--verify", "--quiet", `${ref}^{commit}`], { stdio: "ignore", env: gitEnvironment() }).status === 0;
|
|
82
|
+
|
|
83
|
+
/** The merge base of two commits, or null when they share no history. */
|
|
84
|
+
export function mergeBase(left: string, right: string): string | null {
|
|
85
|
+
const result = spawnSync("git", ["merge-base", left, right], { encoding: "utf8", env: gitEnvironment() });
|
|
86
|
+
return result.status === 0 ? result.stdout.trim() || null : null;
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
/**
|
|
90
|
+
* `binaries.allow` as committed at the commit a change starts from. Only that
|
|
91
|
+
* setting is read, so settings another agent-tool version knows do not hide it.
|
|
92
|
+
* No commit, no agent-tool.json there, or an allowlist that does not parse
|
|
93
|
+
* allows nothing, so a change that adds no binary can still repair it.
|
|
94
|
+
*/
|
|
95
|
+
export function binaryPolicyAt(commit: string | null): BinaryPolicy {
|
|
96
|
+
if (!commit) return { from: null, allow: [] };
|
|
97
|
+
const shown = spawnSync("git", ["cat-file", "blob", `${commit}:agent-tool.json`], { encoding: "utf8", env: gitEnvironment(), maxBuffer: 16 * 1024 * 1024 });
|
|
98
|
+
if (shown.error) return { from: commit, allow: [], error: shown.error.message };
|
|
99
|
+
if (shown.status !== 0) return { from: commit, allow: [] };
|
|
100
|
+
try {
|
|
101
|
+
const config: unknown = JSON.parse(shown.stdout);
|
|
102
|
+
const binaries = config && typeof config === "object" ? (config as { binaries?: unknown }).binaries : undefined;
|
|
103
|
+
const allow = binaries && typeof binaries === "object" ? (binaries as { allow?: unknown }).allow : undefined;
|
|
104
|
+
return { from: commit, allow: binaries === undefined || allow === undefined ? [] : validateBinaryAllow(allow) };
|
|
105
|
+
}
|
|
106
|
+
catch (error) { return { from: commit, allow: [], error: (error as Error).message }; }
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
/** The commit a range starts from: `A` in `A..B`, their one merge base in `A...B`, or the one revision a diff against the working tree names. */
|
|
110
|
+
function rangeBase(range: string): string {
|
|
111
|
+
const revisions = git(["rev-parse", range]).split("\n").filter(Boolean);
|
|
112
|
+
const bases = revisions.filter(line => line.startsWith("^")).map(line => line.slice(1));
|
|
113
|
+
assert(bases.length === 1 || (bases.length === 0 && revisions.length === 1), "Pass --range as <base>..<head>, <base>...<head>, or one revision, so the commit the allowlist is read from is known.");
|
|
114
|
+
return bases[0] ?? revisions[0]!;
|
|
115
|
+
}
|
|
116
|
+
|
|
75
117
|
export function binariesCommand(args: string[]): number {
|
|
76
118
|
const staged = flag(args, "--staged");
|
|
77
119
|
const all = flag(args, "--all");
|
|
@@ -79,22 +121,28 @@ export function binariesCommand(args: string[]): number {
|
|
|
79
121
|
const range = option(args, "--range");
|
|
80
122
|
assert(!args.length && [staged, all, upstream, !!range].filter(Boolean).length <= 1 && !range?.startsWith("-"), "Usage: checks binaries [--staged|--all|--range <range>|--from-upstream]");
|
|
81
123
|
let revisions = staged ? ["--cached"] : all ? ["--cached", git(["hash-object", "-t", "tree", "--stdin"])] : range ? [range] : [];
|
|
124
|
+
// The index is judged by HEAD's committed allowlist, a range by its base's.
|
|
125
|
+
let policyCommit = staged || all ? (commitExists("HEAD") ? git(["rev-parse", "HEAD"]) : null) : range ? rangeBase(range) : null;
|
|
82
126
|
if (!revisions.length) {
|
|
83
|
-
const
|
|
84
|
-
const base =
|
|
127
|
+
const targets = [...(process.env.GITHUB_BASE_REF ? [`refs/remotes/origin/${process.env.GITHUB_BASE_REF}`] : []), "refs/remotes/origin/HEAD", "refs/remotes/origin/main", "refs/remotes/origin/master", "refs/heads/main", "refs/heads/master"];
|
|
128
|
+
const base = ["@{upstream}", ...targets.filter(ref => ref !== "refs/remotes/origin/HEAD")].find(commitExists);
|
|
85
129
|
assert(base, "No upstream/base ref is available; pass --range explicitly."); revisions = [`${base}...HEAD`];
|
|
130
|
+
// The allowlist comes from where HEAD meets the default branch, never from an upstream this branch may already have widened; without one, nothing is allowed.
|
|
131
|
+
const target = targets.find(commitExists);
|
|
132
|
+
policyCommit = target ? mergeBase(target, "HEAD") : null;
|
|
86
133
|
}
|
|
87
134
|
const files = diffBinaries(revisions);
|
|
88
|
-
const
|
|
89
|
-
|
|
135
|
+
const policy = binaryPolicyAt(policyCommit);
|
|
136
|
+
const rejected = rejectedBinaries(files, policy.allow);
|
|
137
|
+
output({ ok: !rejected.length, binaries: files, rejected, policy, ...(rejected.length ? { hint: BINARY_HINT } : {}) }); return rejected.length ? 1 : 0;
|
|
90
138
|
}
|
|
91
139
|
|
|
92
140
|
function diffBinaries(revisions: string[]): string[] {
|
|
93
141
|
return binaryPaths(git(["diff", "--no-ext-diff", "--no-textconv", "--numstat", "-z", "--diff-filter=ACMRT", ...revisions, "--"]));
|
|
94
142
|
}
|
|
95
143
|
|
|
96
|
-
export function rejectedBinaries(files: string[],
|
|
97
|
-
const allowed =
|
|
144
|
+
export function rejectedBinaries(files: string[], allow: string[]): string[] {
|
|
145
|
+
const allowed = allow.map(pattern => new Bun.Glob(pattern));
|
|
98
146
|
return files.filter(file => !allowed.some(pattern => pattern.match(file)));
|
|
99
147
|
}
|
|
100
148
|
|
package/src/workflows/config.ts
CHANGED
|
@@ -35,5 +35,25 @@ export function validateWorkflowConfig(config: WorkflowConfig): void {
|
|
|
35
35
|
if (!entry || typeof entry !== "object" || Object.keys(entry).some(key => !["source", "target", "executable"].includes(key)) || !relativeFile(entry.source) || !/^[a-zA-Z0-9][a-zA-Z0-9._-]*$/.test(entry.target) || typeof entry.executable !== "boolean" || targets.has(entry.target.toLowerCase())) fail("hooks.files");
|
|
36
36
|
targets.add(entry.target.toLowerCase());
|
|
37
37
|
}
|
|
38
|
-
|
|
38
|
+
validateBinaryAllow(config.binaries.allow);
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
/** `binaries.allow` as configured, or an error naming the entry that is not a specific, repository-relative pattern. */
|
|
42
|
+
export function validateBinaryAllow(allow: unknown): string[] {
|
|
43
|
+
if (!Array.isArray(allow) || allow.some(pattern => typeof pattern !== "string" || pattern.startsWith("/") || pattern.includes("..") || !relativeFile(pattern))) throw new Error("Invalid config setting 'binaries.allow'.");
|
|
44
|
+
const broad = (allow as string[]).find(pattern => !specificBinaryPattern(pattern));
|
|
45
|
+
if (broad !== undefined) throw new Error(`Invalid config setting 'binaries.allow': '${broad}' must name a folder before any wildcard, or name one file.`);
|
|
46
|
+
return allow as string[];
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
/** Bun glob syntax; `!` is syntax only at the start, where it negates the whole pattern. */
|
|
50
|
+
const GLOB_SYNTAX = /[*?[\]{}]|^!/;
|
|
51
|
+
|
|
52
|
+
/**
|
|
53
|
+
* An allowlist entry names one file, or names a folder before any wildcard, so
|
|
54
|
+
* an entry cannot admit binaries anywhere in the repository.
|
|
55
|
+
*/
|
|
56
|
+
export function specificBinaryPattern(pattern: string): boolean {
|
|
57
|
+
const [first, ...rest] = pattern.split("/");
|
|
58
|
+
return !GLOB_SYNTAX.test(pattern) || (rest.length > 0 && !GLOB_SYNTAX.test(first!));
|
|
39
59
|
}
|
|
@@ -10,7 +10,7 @@ import { checkInstalledPermissions, PERMISSIONS_MANIFEST } from "../permissions/
|
|
|
10
10
|
import { checkInstalledSkills } from "../skills/install";
|
|
11
11
|
import { SKILLS_MANIFEST } from "../skills/manifest";
|
|
12
12
|
import { branchErrors, parsePrePushInput, pushedBranches, zeroOid, type PushTuple } from "./branch";
|
|
13
|
-
import { binariesAddedByCommits, commitFindings, rejectedBinaries } from "./checks";
|
|
13
|
+
import { BINARY_HINT, binariesAddedByCommits, binaryPolicyAt, commitExists, commitFindings, mergeBase, rejectedBinaries } from "./checks";
|
|
14
14
|
import { assert, checkoutRoot, git, output } from "./core";
|
|
15
15
|
import { checkHooks } from "./hooks";
|
|
16
16
|
import { resolveStep, type StepFinding } from "./pushGateSteps";
|
|
@@ -85,22 +85,25 @@ function gitWithInput(args: string[], input: string): { status: number | null; s
|
|
|
85
85
|
* `git remote set-url`, so subtracting them could skip commits the
|
|
86
86
|
* destination lacks.
|
|
87
87
|
*/
|
|
88
|
-
export function listDestination(remote: string, pushUrl: string, list = true): PushDestination & { commits: string[] } {
|
|
88
|
+
export function listDestination(remote: string, pushUrl: string, list = true): PushDestination & { commits: string[]; head: string | null } {
|
|
89
89
|
const configured = /^[a-zA-Z0-9][a-zA-Z0-9._-]*$/.test(remote) && spawnSync("git", ["remote", "get-url", remote], { stdio: "ignore", env: gitEnvironment() }).status === 0;
|
|
90
90
|
const name = configured ? remote : null;
|
|
91
91
|
// Only the redacted URL is reported; the real one is used to list refs.
|
|
92
92
|
const url = redactUrl(pushUrl);
|
|
93
|
-
if (!list) return { name, url, advertised: null, error: null, commits: [] };
|
|
93
|
+
if (!list) return { name, url, advertised: null, error: null, commits: [], head: null };
|
|
94
94
|
assert(!pushUrl.startsWith("-"), "The push URL must not start with '-'.");
|
|
95
95
|
// Never prompt for credentials or wait forever: a failed listing falls back to the old tip Git reported.
|
|
96
96
|
const listed = spawnSync("git", ["ls-remote", pushUrl], { encoding: "utf8", stdio: ["ignore", "pipe", "pipe"], env: { ...gitEnvironment(), GIT_TERMINAL_PROMPT: "0" }, maxBuffer: 256 * 1024 * 1024, timeout: LIST_TIMEOUT_MS, killSignal: "SIGKILL" });
|
|
97
|
-
if (listed.error || listed.status !== 0) return { name, url, advertised: null, error: redactUrl(listed.stderr || listed.error?.message || "git ls-remote failed").replaceAll(pushUrl, url).trim(), commits: [] };
|
|
98
|
-
const
|
|
99
|
-
|
|
97
|
+
if (listed.error || listed.status !== 0) return { name, url, advertised: null, error: redactUrl(listed.stderr || listed.error?.message || "git ls-remote failed").replaceAll(pushUrl, url).trim(), commits: [], head: null };
|
|
98
|
+
const lines = listed.stdout.split("\n").map(line => line.split("\t"));
|
|
99
|
+
const candidates = [...new Set(lines.map(([oid]) => oid!).filter(oid => fullOid.test(oid)))];
|
|
100
|
+
if (!candidates.length) return { name, url, advertised: 0, error: null, commits: [], head: null };
|
|
100
101
|
const checked = gitWithInput(["cat-file", "--batch-check=%(objectname) %(objecttype)"], candidates.map(oid => `${oid}^{commit}`).join("\n") + "\n");
|
|
101
102
|
assert(checked.status === 0, `Could not inspect the destination's advertised commits: ${checked.stderr.trim()}`);
|
|
102
103
|
const commits = [...new Set(checked.stdout.split("\n").filter(line => line.endsWith(" commit")).map(line => line.split(" ", 1)[0]!))];
|
|
103
|
-
|
|
104
|
+
// The destination's default branch tip, when it advertises HEAD and this clone has that commit.
|
|
105
|
+
const advertisedHead = lines.find(([, ref]) => ref === "HEAD")?.[0];
|
|
106
|
+
return { name, url, advertised: commits.length, error: null, commits, head: advertisedHead && commits.includes(advertisedHead) ? advertisedHead : null };
|
|
104
107
|
}
|
|
105
108
|
|
|
106
109
|
const isCommit = (value: string) => spawnSync("git", ["cat-file", "-e", `${value}^{commit}`], { stdio: "ignore", env: gitEnvironment() }).status === 0;
|
|
@@ -157,6 +160,19 @@ function guard(guards: Guard[], name: string, ref: string | undefined, check: ()
|
|
|
157
160
|
guards.push({ name, ...(ref ? { ref } : {}), ...result, durationMs: Math.round(performance.now() - started) });
|
|
158
161
|
}
|
|
159
162
|
|
|
163
|
+
/**
|
|
164
|
+
* The commit a pushed ref's binaries are judged from: where its tip meets the
|
|
165
|
+
* destination's default branch, from the HEAD the destination advertises,
|
|
166
|
+
* else from this clone's tracking ref of it; without either, null, which
|
|
167
|
+
* allows nothing. The branch's own old tip never counts, since an earlier push
|
|
168
|
+
* of the branch could have widened the allowlist.
|
|
169
|
+
*/
|
|
170
|
+
function binaryPolicyBase(ref: PushedRef, destination: { name: string | null; head: string | null }): string | null {
|
|
171
|
+
const tracking = destination.name ? ["HEAD", "main", "master"].map(branch => `refs/remotes/${destination.name}/${branch}`) : [];
|
|
172
|
+
const target = destination.head ?? tracking.find(commitExists);
|
|
173
|
+
return target ? mergeBase(ref.localOid, target) : null;
|
|
174
|
+
}
|
|
175
|
+
|
|
160
176
|
/** The built-in trust guards, from the same implementations as `hooks check`, `skills check`, `permissions check`, `branch check --pre-push`, `commits check`, and `checks binaries`. */
|
|
161
177
|
function runGuards(root: string, config: AgentToolConfig, tuples: PushTuple[], destination: ReturnType<typeof listDestination>): { guards: Guard[]; refs: PushedRef[] } {
|
|
162
178
|
const guards: Guard[] = [];
|
|
@@ -172,7 +188,11 @@ function runGuards(root: string, config: AgentToolConfig, tuples: PushTuple[], d
|
|
|
172
188
|
guard(guards, "ranges", undefined, () => { refs = pushedRefs(tuples, destination); return { ok: true }; });
|
|
173
189
|
for (const ref of refs.filter(item => !item.deleted)) {
|
|
174
190
|
guard(guards, "commits", ref.remoteRef, () => { const findings = commitFindings(ref.commits, config); return { ok: !findings.length, details: { checked: ref.commits.length, findings } }; });
|
|
175
|
-
guard(guards, "binaries", ref.remoteRef, () => {
|
|
191
|
+
guard(guards, "binaries", ref.remoteRef, () => {
|
|
192
|
+
const policy = binaryPolicyAt(binaryPolicyBase(ref, destination));
|
|
193
|
+
const rejected = rejectedBinaries(binariesAddedByCommits(ref.commits), policy.allow);
|
|
194
|
+
return { ok: !rejected.length, details: { rejected, policy, ...(rejected.length ? { hint: BINARY_HINT } : {}) } };
|
|
195
|
+
});
|
|
176
196
|
}
|
|
177
197
|
return { guards, refs };
|
|
178
198
|
}
|
|
@@ -204,7 +224,7 @@ export async function runPushGate(args: string[], root: string): Promise<number>
|
|
|
204
224
|
if (!gate) notes.push("agent-tool.json declares no pushGate section; only the built-in guards ran.");
|
|
205
225
|
// Deletions alone push nothing, so they need no listing of the destination.
|
|
206
226
|
const destination = listDestination(remote, url, tuples.some(tuple => !zeroOid(tuple.localOid)));
|
|
207
|
-
const { commits: _advertised, ...remoteInfo } = destination;
|
|
227
|
+
const { commits: _advertised, head: _head, ...remoteInfo } = destination;
|
|
208
228
|
const { guards, refs } = runGuards(root, config, tuples, destination);
|
|
209
229
|
const failed = guards.filter(item => !item.ok);
|
|
210
230
|
for (const item of failed) {
|