@a2f0/agent-tool 0.1.17 → 0.1.18

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.
@@ -1,9 +1,9 @@
1
- // Generated by scripts/bundle-skills.ts; edit skills/*/SKILL.md.
1
+ // Generated by scripts/build/bundle-skills.ts; edit skills/*/SKILL.md.
2
2
  export const BUNDLED_SKILLS: Readonly<Record<string, string>> = {
3
- "cross-agent-review": "---\nname: cross-agent-review\ndescription: Review committed branch changes with an independent 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 a reviewer different from the coordinating agent when possible. Honor a\nrequested reviewer or effort; otherwise use an 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 claude`, `agent-tool review codex`,\nor `agent-tool review opencode`. Optional effort is `low`, `medium`, `high`,\n`xhigh`, or `max`. For a local or non-GitHub repository, add `--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\nRecord 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.\n\nIf a CLI is unavailable, out of credits, or returns an unusable review, try another\navailable reviewer and disclose the fallback. Do not silently convert a failed\nreview into CLEAN or call an in-session review independent.\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. Report reviewer, exact base and head IDs, verdict,\nremaining findings, validation, and any repairs performed. This skill does not\nauthorize pushing, opening a PR, or merging unless the user requested that work.\n",
4
- "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 Git and `gh`;\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 push it through the\nrepository's normal push workflow, naming the PR repository's remote and branch\nexplicitly, as in `git push -u origin HEAD`; a bare push follows whatever\nupstream the branch tracks, which may be a local branch. Respect existing push\nauthorization; do not bypass hooks. If the user only requested a draft\ndescription, prepare that text without publishing a PR.\n\nWrite a title that satisfies the data-only `agent-tool.json` subject policy.\nDescribe the concrete resulting behavior and relevant validation. Put multiline\nbody text in a temporary file, then run:\n\n```sh\nagent-tool pr open 'feat: describe the change' < /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.\n",
5
- "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\nCheck worktree and index first. Preserve user edits; if they prevent switching,\nreport the condition instead of discarding or automatically stashing them. For\npost-merge cleanup, confirm the PR is MERGED before removing a feature branch.\n\nFetch the default branch, switch to it, and update by fast-forward only. A\ndiverged default branch requires inspection rather than forced replacement.\nDelete a merged feature branch only within the requested cleanup scope and\nafter verifying its exact commit is the shipped commit; squash merging does not\nmake Git ancestry-based branch deletion proof of shipping. Honor keep-branch.\n\nRun only the hook installer or dependency setup documented by this repository\nwhen the updated checkout requires it. Do not assume a package manager or copy\nsetup commands from another project. Report final branch, commit, and any\nunfinished cleanup.\n",
6
- "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 installation remain project\nconcerns. 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`, and other commands whose output drives a decision directly.\nPrefer documented compact test reporters when they preserve required evidence;\ndo not reduce test scope, skip checks, silence warnings, or mask failures.\n\n1. Finish the requested change on a feature branch. Create it with\n `git switch --no-track -c <branch>`; settings such as\n `branch.autosetupmerge=always` otherwise make it track a local branch.\n Validate it with appropriate project checks and commit only the intended\n files.\n2. Determine the current PR's base repository and branch, or the repository's\n default branch when no PR exists. Fetch and pin its exact base. Integrate it\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.\n3. Push the reviewed HEAD through normal hooks, then verify the pushed SHA still\n equals the reviewed SHA. If a hook changed content or HEAD, review that result.\n Open the PR using the open-pr skill, or update the existing PR as needed.\n4. Allow any configured review bots time to respond, then fetch unresolved PR\n review threads. Follow repository policy for feedback: fix valid findings,\n reply in the original threads, and resolve only fully addressed comments.\n Validate, commit, push, and independently review every feedback or CI repair.\n Wait for CI, recheck the live base, PR base branch, and local and remote heads.\n A changed base requires integration, validation, and another review. When\n versions are managed, `agent-tool versions check <base-oid>` must pass for the\n live base. Use the squash-merge skill to merge the exact reviewed HEAD.\n5. After confirmed MERGED, honor keep-branch; otherwise use the reset skill to\n return to the updated default branch and apply any documented project setup.\n6. When the project deploys the merged branch, verify the deployment for the\n merge commit and run its documented live checks. Report deployment failures\n separately from a successful merge; follow project policy for repairs.\n\nNever infer a clean review from process success alone or carry a review across\ncontent changes. Do not weaken configured CI policy to get a merge through.\nIf a step fails, preserve useful intermediate work and report the concrete\nremaining issue. Report PR link, merged commit, review verdict, validation, and\nfinal checkout state.\n",
7
- "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 for required checks using `gh pr checks --watch --fail-fast`. Refresh the\nPR and live base from the repository that owns the PR. Confirm local HEAD and PR\nHEAD both equal the reviewed commit, the base branch is unchanged, the live base\nstill equals the reviewed base, and that base is an ancestor of reviewed HEAD.\nIf any identity changed, refresh, validate, and review again.\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;\nrepository branch protection must enforce any required base freshness. 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. Report the PR and merge result.\n",
3
+ "cross-agent-review": "---\nname: cross-agent-review\ndescription: Review committed branch changes with an independent 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 a reviewer different from the coordinating agent when possible. Honor a\nrequested reviewer or effort; otherwise use an 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 claude`, `agent-tool review codex`,\nor `agent-tool review opencode`. Optional effort is `low`, `medium`, `high`,\n`xhigh`, or `max`. For a local or non-GitHub repository, add `--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.\n\nIf a CLI is unavailable, out of credits, or returns an unusable review, try another\navailable reviewer and disclose the fallback. Do not silently convert a failed\nreview into CLEAN or call an in-session review independent.\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. Report reviewer, exact base and head IDs, verdict,\nremaining findings, validation, and any repairs performed. This skill does not\nauthorize pushing, opening a PR, or merging unless the user requested that work.\n",
4
+ "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. Put multiline\nbody text in a temporary file, then run:\n\n```sh\nagent-tool pr open 'feat: describe the change' < /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.\n",
5
+ "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, preserves\nlocal edits, checks exact local/remote feature commits, verifies the merge is on\nthe default branch, and fast-forwards that branch. Pass `--keep-branch` when the\nuser asked to preserve feature refs. Read the receipt's completed steps if a\nlater operation fails; do not claim full cleanup from a partial result.\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.\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 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, and unfinished\ncleanup or setup.\n",
6
+ "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`, and other commands whose output drives a decision directly.\nPrefer documented compact test reporters when they preserve required evidence;\ndo not reduce test scope, skip checks, silence warnings, or mask failures.\n\n1. 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.\n Validate it with appropriate project checks and commit only the intended\n files.\n2. 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.\n3. 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.\n4. 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>`, then run\n `agent-tool pr preflight <reviewed-head> <base-branch> <reviewed-base>` to\n recheck CI, live base, PR identity, local state, and explicit version policy.\n A changed base requires integration, validation, and another review. When\n versions are managed, `agent-tool versions check <base-oid>` must pass for the\n live base. Use the squash-merge skill to merge the exact reviewed HEAD.\n5. After confirmed MERGED, honor keep-branch; otherwise use the reset skill to\n return to the updated default branch and apply any documented project setup.\n6. 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.\n\nNever infer a clean review from process success alone or carry a review across\ncontent changes. Do not weaken configured CI policy to get a merge through.\nIf a step fails, preserve useful intermediate work and report the concrete\nremaining issue. Report PR link, merged commit, review verdict, validation, and\nfinal checkout state.\n",
7
+ "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. Run\n`agent-tool pr preflight <reviewed-head> <base-branch> <reviewed-base>` immediately\nbefore merging. It checks local and PR identity, live base, ancestry, explicit\nversion policy, merge readiness, configured strict rulesets, and passing checks.\nIf an identity changed, refresh, integrate, validate, and review again. Read\nunresolved feedback with `pr threads list` and follow project 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;\nrepository branch protection must enforce any required base freshness. 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. Report the PR and merge result.\n",
8
8
  "update-dependencies": "---\nname: update-dependencies\ndescription: Update repository dependencies, runtimes, tools, and CI pins with compatibility checks and safe infrastructure previews, then ship through review, CI, merge, and release verification unless a narrower scope is requested.\n---\n\n# Update Dependencies\n\nUse the repository's package managers and installed `agent-tool`. Read `AGENTS.md`,\nREADME, existing dependency-maintenance notes, linked setup/release documents,\nand repository-owned upgrade skills before editing. Follow their hooks, version\npolicy, checks, and requested stopping point.\nUpdate applicable dependencies throughout the repository, including workspaces\nand examples. When asked to perform dependency updates, invoke the installed\n[`ship-pr`](../ship-pr/SKILL.md) to complete review, PR, CI, and merge, then verify\nthe repository's normal merge-triggered publication or deployment. An explicit\nnarrower scope, such as inventory-only, local changes, or open-PR-only, takes\nprecedence. This default does not authorize standalone infrastructure applies,\ndeployments, or global tool changes. Default dependency-update merge subject:\n`chore: update dependencies`, subject to repository title policy and any explicit\nuser subject.\n\nRun noisy installs, checks, tests, and builds with\n`agent-tool run --label <check> -- <command> [args...]` to retain full private\nlogs and return the original status with compact output. Inspect bounded excerpts\nusing `agent-tool logs <log>` and targeted searches for warnings and evidence;\na successful receipt does not establish a warning-free upgrade. Keep structured\naudit/plan results, deployment previews, and review findings directly visible\nwhen they drive a safety decision. Do not dump full suite logs into context,\nsilence warnings at their source, or change check scope to reduce output.\n\n## Safety before execution\n\n**Always dry-run before any infrastructure apply or deployment. Never destroy,\nreplace, or recreate a resource during an upgrade.** This includes Terraform,\nOpenTofu, Wrangler, Ansible, other infrastructure tools, and effects triggered by\ninstallation, tests, hooks, Git push, opening a PR, CI, or merging. Greenfield\nprojects and approval to ship do not waive this rule.\n\nBefore running project commands or pushing, trace their scripts, hooks, workflow\ntriggers, reusable workflows, and deployment commands. A dry-run flag alone is\ninsufficient: inspect tasks, provisioners, plugins, external programs, and actions\nthat can mutate despite preview mode. Avoid such a preview unless its effects\nare proven read-only. Do not run destroy/delete, taint/replace, state removal,\nbackend migration, forced database reset, or an automatic \"repair\" that bypasses\nthe rule. Do not hide destruction with targeting, disabled refresh, ignored\nchanges, new resource identities, or weakened policy.\n\nPreview with the proposed versions and complete configuration for each affected\nenvironment, using its real backend/workspace/account, variables, inventory, and\nresource identities. An empty local state, mocked credentials, validate-only run,\nor bundle build cannot establish safety for production. Check the current baseline\nas well when needed to distinguish existing drift from the upgrade. Keep state,\nbinary plans, JSON plans, and secret-bearing diffs out of Git and public reports.\n\nIf a preview proposes deletion or replacement, fails, is incomplete, omits\naffected resources, or cannot establish safety, skip that dependency and its\ncoupled migrations. Restore only this task's edits to the affected compatibility\ngroup, retain independent safe upgrades, and record the reason and affected\nresources. Never apply to find out. A preview is not deployment authorization.\n\nBefore an authorized apply/deploy, verify the exact validated commit, toolchain,\nconfiguration, environment, and current state still match the preview. Re-preview\nafter relevant changes or drift. CI must enforce the same order and stop on an\nunsafe preview before mutation; a successful local preview does not excuse an\nunguarded push- or merge-triggered deployment. Establish a narrowly scoped guard\nwhen authorized and reviewable, or hold the affected upgrade before triggering\nthat workflow. Do not disable protections to ship. A plan must be inspected before\nthe operation; inspecting deployment logs afterward is too late.\nAn unsafe workflow triggered on every branch push also blocks pushing otherwise\nindependent upgrades until that trigger has a proven safe guard.\n\n### Terraform and OpenTofu\n\nRead core, provider, and module upgrade guides, including intermediate major\nmigrations. Regenerate provider locks with the pinned CLI, preserving supported\nplatform hashes. Backend initialization/migration is also subject to the safety\ngate. Inspect external data programs and provisioners before planning.\n\nUse a full refreshed saved plan with locking and the real variables, for example\n`terraform plan -input=false -out=<private-plan>`; if using `-detailed-exitcode`,\n0 and 2 are success, 1 is failure. Inspect `terraform show -json <private-plan>`.\nRun `agent-tool dependencies check-terraform-plan <private-plan.json>` to check\nsupported JSON resource actions. It fails for every action containing `delete`,\nincluding both replacement orders, unknown actions, incomplete/deferred plans,\nfailed checks, or opaque provider action invocations. It prints actions and\ndiagnostics without resource attribute values; it does not prove that a plan is\nfresh, comprehensive, authentic, or that provider code has no hidden effects.\nOlder/unsupported plan formats that cannot establish completeness are skipped.\nOpenTofu currently omits `complete` in its JSON format and is rejected by this\nhelper; report that limitation rather than adding a synthetic completeness flag.\nAlso inspect resource identity, drift, warnings, provider semantics, and any\neffects outside resource actions. For an authorized apply, consume the exact\napproved saved plan, not an uninspected newly generated plan.\n\nSource: [Terraform JSON plan format](https://developer.hashicorp.com/terraform/internals/json-format).\n\n### Wrangler and other deployment tools\n\nUse the proposed pinned Wrangler for `wrangler deploy --dry-run` with the same\nbuild/configuration/environment used by deployment. This checks bundling, not a\ncomplete remote resource plan. Separately verify account, worker name, routes,\nbindings and resource IDs against the existing deployment and read migration\nsemantics. Review Durable Object deleted/renamed classes, D1 schema/data\nmigrations, storage resources, queues, containers, and deployment integrations.\nNever infer \"no destruction\" from a successful bundle. Resource removals,\nreplacement, or unprovable remote effects skip the affected group. Apply the\nequivalent preview and identity checks to other tools rather than assuming they\nshare Terraform's guarantees.\n\nDo not assume `wrangler d1 migrations list --remote` is read-only. The\nimplementation inspected for this skill initializes migration tracking with\n`CREATE TABLE IF NOT EXISTS`; verify the pinned Wrangler version before using\nthe command. Verify database identity and compare migration files with the\ndatabase's configured migration tracking table through audited read-only\nqueries. A missing table, pending migration, or unverifiable schema/data\neffects hold the affected upgrade/deployment group. Never initialize schema\nmerely to establish preview safety.\n\nWrangler runs a custom `build.command` again during deployment. Use supported\nconfiguration referencing the same validated artifacts for both preview and\ndeployment, preventing another unvalidated build before upload. Bind the\nartifacts, configuration, and pinned tool to the authorized commit, and recheck\ntheir identities before upload and after relevant changes. Hold the affected\ngroup if the pinned Wrangler cannot upload the validated output without\nrebuilding it, or if the upload cannot be proven to match the preview.\n\nSources: [Wrangler command documentation](https://developers.cloudflare.com/workers/wrangler/commands/),\n[D1 migration listing implementation](https://github.com/cloudflare/workers-sdk/blob/e3d186776fcc2e4b5cc4cfd7155591778a375957/packages/wrangler/src/d1/migrations/list.ts),\n[migration table initialization](https://github.com/cloudflare/workers-sdk/blob/e3d186776fcc2e4b5cc4cfd7155591778a375957/packages/wrangler/src/d1/migrations/helpers.ts),\nand [Wrangler custom builds](https://developers.cloudflare.com/workers/wrangler/custom-builds/).\n\n### Ansible\n\nCheck controller Python, ansible-core, collections/roles, and target Python support\ntogether; read porting guides. Inspect all tasks and invoked scripts before\n`ansible-playbook --check --diff` with the real inventory and variables.\n`check_mode: false` forces mutation even with `--check`; unsupported modules and\nconditions based on registered results can omit effects. Inspect deletion,\nrecreation, service/data reset, and package removal semantics beyond the diff.\nSkipped or opaque tasks are a safety gap, not a clean preview. Redact diffs.\n\nSource: [Ansible check mode limits](https://docs.ansible.com/projects/ansible/latest/playbook_guide/playbooks_checkmode.html).\n\n## Inventory and choose compatible targets\n\nRecord each dependency source, current resolved version, latest stable candidate,\nselected target, compatibility constraints, upstream migration links, and checks\nin the run ledger described under Report.\nQuery authoritative registries, official releases, support matrices, and migration\nguides at execution time; do not treat remembered versions or prereleases as\nlatest stable. Inspect runtime requirements, peer dependencies, ABI/API changes,\nplatform availability, maintained release lines, and changed defaults, including\nsecurity, privacy/telemetry, data retention, and postinstall/native behavior.\nCheck transitive dependencies' peer/runtime constraints as well as direct ones. Unsupported\nor unpublished targets stay pinned with an explanation.\n\nInventory manifests, locks, tool configuration, CI/reusable actions, containers,\nscripts, deployment files, and executable documentation. Search duplicate version\npins and aliases, not just filenames; exclude vendored/generated snapshots unless\nthe repository owns their update process. Examples of sources to inspect:\n\n| Ecosystem | Sources and compatibility group |\n| --- | --- |\n| JavaScript/TypeScript | All package.json dependency fields, overrides/resolutions, workspace catalogs, packageManager/engines, npm/Bun/pnpm/Yarn locks, Node/Bun pins, compiler and lint/build/test plugins |\n| Toolchains | mise.toml/.mise.toml, mise.lock, .tool-versions, runtime version files, tool URLs/checksums, CI pins and container images; include every tool declared by mise, not just mise itself |\n| Python/Ansible | pyproject/requirements, uv/Poetry/pip locks, Python pins, ansible-core, collection/role requirements, lint plugins and managed host constraints |\n| Ruby/iOS | .ruby-version, Gemfile/lock, Bundler, CocoaPods, Podfile/lock, podspecs, Swift packages and Xcode/iOS deployment requirements |\n| Infrastructure | Terraform/OpenTofu CLI constraints, provider locks/constraints, module versions/Git refs, Wrangler and Cloudflare integration dependencies |\n| CI/system/native | Actions/reusable workflow refs, Docker tags/digests, OS images/packages, Rust/Cargo toolchain and locks, Go modules, Gradle/AGP/Kotlin/JDK and other repository-specific manifests |\n\nBuild connected compatibility groups before editing. Select the newest supported\ncombination, which can be older than an individual package's latest. Upgrade the\nframework first or keep its compatible toolchain pinned; do not force peer\nresolution, drop compatibility checks, or add blanket overrides to make installs\npass. Preserve source pin policy (exact version, digest, full Git SHA) and resolve\nimmutable pins from verified upstream releases. Preserve intentional runtime\nminimums unless migration requires changing the support contract.\n\nFor React Native, use its version-specific upgrade guide/template diffs and\nrepository upgrade skills. Couple React and its renderer, native modules,\nMetro/Babel, CLI, codegen, Hermes/New Architecture, CocoaPods/Bundler/Ruby,\nXcode/iOS deployment targets, and Android Gradle/AGP/Kotlin/JDK/SDK/NDK. For Expo,\nuse the chosen SDK's supported React Native/dependency matrix and its dependency\nchecks. Do not independently update framework-managed pods or generated native\nfiles; use the framework's regeneration workflow and prove iOS/Android builds.\nPermissive peer ranges alone do not prove native renderer or toolchain compatibility;\ncheck the framework's actual supported versions and native implementation.\nAn unavailable native toolchain is a reported validation limit; do not claim the\ngroup verified. See [React Native upgrading](https://reactnative.dev/docs/upgrading).\n\nCheck developer tools' own dependencies too: a compiler release without its old\nprogrammatic API may break test/lint runners that import it even when `tsc` passes.\nAction runtime upgrades can require newer self-hosted runners; preserve workflow\npermissions, action inputs/outputs, caching, artifact semantics, and job names.\n\nCheck current advisories with read-only ecosystem audits against the baseline and\nproposed lockfiles, using the repository's configured registry/advisory sources.\nDo not send private dependency metadata to an unconfigured or unauthorized service;\nreport the resulting coverage limit. Cover direct and resolved transitive dependencies,\nincluding native/platform-specific binaries. Latest direct packages can still\npin vulnerable transitive versions. Trace each finding to its owning dependency,\nverify affected versions, runtime conditions, and remediation in the maintainer's\nadvisory and fixed release. When the owner's range permits a fixed version, use a\ntargeted refresh with the lockfile's owning manager and preserve unrelated\nresolutions; otherwise prefer a supported owner upgrade.\nIf the owner still pins a vulnerable version, a narrowly scoped security patch\noverride may be used only with API/ABI/runtime compatibility evidence and focused\nregression checks of the actual affected integration. Document its rationale and\nremoval condition; a passing install or bundle alone is insufficient. Do not run\nblind audit fixes or use blanket overrides to bypass compatibility constraints.\nReport unresolved advisories and unavailable audit coverage accurately; current\ndirect pins or a partial clean audit do not\nestablish that the whole dependency graph is safe.\n\n## Migrate and validate\n\nCapture relevant baseline checks and warnings first, after screening their side\neffects. Update one compatibility group at a time. Read the upstream instructions\nfor every breaking step; implement required source/config/schema migrations and\nremoved API replacements. Use the manager that owns each lockfile, on the selected\nruntime, and inspect the resulting diff. Refresh transitive dependencies through\ntheir owning direct dependency; do not hand-edit integrity hashes or lock entries.\nReview intentional patches, overrides, and pins before removal; retain them until\nupstream fixes and regression checks demonstrate they are unnecessary.\nAvoid unrelated global installations or environment changes. Use task-local or\nrepository-scoped tools for testing changed runtime pins.\nFor published packages, also validate tarballs and consumer installs with their\ndocumented supported package managers, including manifest/override syntax and\nruntime requirements. A successful owning-manager install does not prove that\npublished metadata works for those consumers.\n\nRun the repository's setup/hooks, frozen installs, lint, typechecks, tests, builds,\npackage/platform smoke checks, and relevant safe integration previews. Resolve\nupgrade-related deprecation warnings at their source. Do not suppress warnings,\nweaken tests, or disable checks; report remaining upstream/pre-existing warnings\nwith evidence and keep a target pinned when migration cannot be completed.\nAdd focused regression coverage when a migration changes behavior; avoid tests\nthat merely assert version strings. Re-run checks after repairs. Report checks\nblocked by missing credentials, platforms, or external services accurately.\nRe-audit the final resolved graph after migrations and repairs.\n\nConfirm every inventory row is upgraded, already current, intentionally constrained,\nor skipped with a concrete reason. Do not present an unresolved group as complete.\nWhen upgrading agent-tool itself, install its managed skills with the same harness\nscope and commit the ownership manifest; never edit generated managed skill copies.\n\nWhen changes depend on another repository's release, ship the producer first and\nconfirm publishing and registry availability before pinning the consumer; include\nits exact version/commit and API migration notes. Independent groups may proceed.\nComplete the installed `ship-pr` workflow within the requested scope, including\nindependent review of every changed HEAD, required CI and review feedback, merge,\nand verification of the merge's normal publication or deployment. Do not stop at\nan open PR unless the user requested that stopping point or a concrete blocker\nprevents continuing. Check deployment safety again before push/open/merge;\nshipping defaults do not waive the preview gates above.\n\n## Report\n\nKeep run-specific evidence in the upgrade PR body or a linked PR comment: the\ninventory and old/selected versions, completed migrations, validation and warnings,\nbaseline/final audits and coverage limits, preview environment/commit/tool versions\nand safe action summary, and skipped/constrained dependencies with reasons. Include\nsecurity overrides, their rationale and removal condition, and unresolved advisories.\nIf the user requested a scope that stops before a PR, provide this ledger in the\ntask report and honor that limit. For a sweep, keep one entry per repository,\nincluding unready and unchanged checkouts, and use an existing tracking issue only\nwhen explicitly requested. Never create an issue merely to store upgrade evidence.\n\nKeep durable repository guidance focused on what the next upgrade needs: current\ncompatibility constraints, intentional pins/overrides, unresolved advisories, and\nreusable repository-specific procedures. Prefer the existing maintenance document;\notherwise create `docs/dependency-upgrades.md` (or the repository's equivalent)\nonly when there is substantive guidance to preserve. For each constraint, record\nits rationale, upstream advisory/migration/issue link or originating PR, and the\ncondition and check for removing or revisiting it. Do not copy version inventories,\naudit output, validation/preview receipts, or dated run journals into that document.\n\nOn every upgrade, reconcile the existing maintenance document against the final\ndependency graph and checks: update constraints in place, remove resolved entries,\nand link the PR for historical evidence. Keep the root README focused on purpose,\nsetup, supported requirements, and normal usage, with a concise maintenance link\nwhen needed. Keep dependency-maintenance guidance in `AGENTS.md` to a short\nrouting rule and link; do not accumulate upgrade reports in either entrypoint\nor duplicate the maintenance document.\n\nFor shipping, report the branch, reviewed commit/verdict, PR, merge, publish/deploy\nresult, and final checkout state. Keep full logs private; never publish credentials,\nstate, or plan contents in any of these locations.\n"
9
9
  };
@@ -0,0 +1,80 @@
1
+ import { spawnSync } from "node:child_process";
2
+ import { readFileSync } from "node:fs";
3
+ import { loadConfig, type AgentToolConfig } from "../config";
4
+ import { remoteBranchHead } from "../git/prContext";
5
+ import { gitEnvironment } from "../git/environment";
6
+ import { assert, clean, currentBranch, flag, git, head, mutateGit, nativeBranch, oid, option, output, repository } from "./core";
7
+
8
+ export function branchErrors(name: string, config: AgentToolConfig): string[] {
9
+ const errors: string[] = [];
10
+ if (!nativeBranch(name)) errors.push("Invalid Git branch ref.");
11
+ if (!config.branch.enforce || config.branch.exempt.includes(name)) return errors;
12
+ if (config.branch.maxLength !== null && name.length > config.branch.maxLength) errors.push(`Branch exceeds ${config.branch.maxLength} characters.`);
13
+ const match = /^([a-z][a-z0-9-]*)\/([a-z0-9][a-z0-9._-]*(?:\/[a-z0-9][a-z0-9._-]*)*)$/.exec(name);
14
+ if (!match || !(config.branch.types ?? config.subject.types).includes(match[1]!)) errors.push("Expected <type>/<lowercase-topic> using configured branch types.");
15
+ return errors;
16
+ }
17
+
18
+ export function remoteUrl(remote: string, push = false): string {
19
+ assert(/^[a-zA-Z0-9][a-zA-Z0-9._-]*$/.test(remote), "Expected a named Git remote.");
20
+ const urls = git(["remote", "get-url", ...(push ? ["--push"] : []), "--all", remote]).split("\n");
21
+ assert(urls.length === 1 && !!urls[0], "Remote must have exactly one destination URL.");
22
+ return urls[0]!;
23
+ }
24
+
25
+ export function branchCommand(args: string[]): number {
26
+ const action = args.shift();
27
+ const config = loadConfig();
28
+ if (action === "check") {
29
+ const prePush = flag(args, "--pre-push");
30
+ assert(!prePush || !args.length, "--pre-push reads destination refs from stdin and accepts no names.");
31
+ assert(!args.some(arg => arg.startsWith("-")), "Usage: branch check [name...]");
32
+ const names = prePush ? readFileSync(0, "utf8").split("\n").filter(line => line.trim()).flatMap(line => {
33
+ const fields = line.trim().split(/\s+/);
34
+ assert(fields.length === 4 && /^(?:[a-f0-9]{40}|[a-f0-9]{64})$/i.test(fields[1]!) && /^(?:[a-f0-9]{40}|[a-f0-9]{64})$/i.test(fields[3]!), "Malformed Git pre-push input.");
35
+ return /^0+$/.test(fields[1]!) || !fields[2]!.startsWith("refs/heads/") ? [] : [fields[2]!.slice("refs/heads/".length)];
36
+ }) : args.length ? args : [currentBranch()];
37
+ const results = names.map(name => ({ name, errors: branchErrors(name, config) }));
38
+ const ok = results.every(result => !result.errors.length);
39
+ output({ ok, branches: results }); return ok ? 0 : 1;
40
+ }
41
+ if (action === "status") {
42
+ assert(!args.length, "Usage: branch status");
43
+ output({ branch: git(["branch", "--show-current"]) || null, headOid: head(), status: git(["status", "--porcelain=v1", "--branch"]), upstream: spawnSync("git", ["rev-parse", "--abbrev-ref", "@{upstream}"], { encoding: "utf8", env: gitEnvironment() }).stdout?.trim() || null });
44
+ return 0;
45
+ }
46
+ const remote = option(args, "--remote") ?? "origin";
47
+ if (action === "create") {
48
+ const base = option(args, "--base") ?? repository().defaultBranchRef.name;
49
+ assert(args.length === 1 && nativeBranch(base), "Usage: branch create <name> [--base <branch>] [--remote <name>]");
50
+ const name = args[0]!;
51
+ const errors = branchErrors(name, config);
52
+ assert(!errors.length, errors.join(" "));
53
+ assert(!config.branch.exempt.includes(name) && name !== base, "Create requires a feature branch.");
54
+ clean();
55
+ assert(spawnSync("git", ["show-ref", "--verify", "--quiet", `refs/heads/${name}`], { env: gitEnvironment() }).status === 1, `Local branch '${name}' exists or could not be checked.`);
56
+ const url = remoteUrl(remote);
57
+ assert(!remoteBranchHead(url, name), `Remote branch '${name}' already exists.`);
58
+ const pushUrl = remoteUrl(remote, true);
59
+ if (pushUrl !== url) assert(!remoteBranchHead(pushUrl, name), `Push destination branch '${name}' already exists.`);
60
+ const baseOid = remoteBranchHead(url, base);
61
+ assert(baseOid, `Remote base '${base}' does not exist.`);
62
+ git(["fetch", "--no-tags", remote, `refs/heads/${base}`]);
63
+ assert(git(["rev-parse", "FETCH_HEAD"]) === baseOid && remoteBranchHead(url, base) === baseOid, "Base moved while fetching; retry creation.");
64
+ mutateGit(["switch", "--no-track", "-c", name, oid(baseOid)]);
65
+ assert(currentBranch() === name && head() === baseOid, "Checkout changed during branch creation.");
66
+ output({ branch: name, headOid: baseOid, baseBranch: base, baseOid, remote }); return 0;
67
+ }
68
+ assert(action === "push" && args.length === 1, "Usage: branch push <expected-head-oid> [--remote <name>]");
69
+ const expected = oid(args[0]!);
70
+ const branch = currentBranch();
71
+ const errors = branchErrors(branch, config);
72
+ assert(!errors.length && !config.branch.exempt.includes(branch) && branch !== repository().defaultBranchRef.name, errors.join(" ") || "Push requires a feature branch.");
73
+ clean();
74
+ assert(head() === expected, "HEAD differs from the reviewed commit.");
75
+ const url = remoteUrl(remote, true);
76
+ mutateGit(["push", "--set-upstream", remote, `HEAD:refs/heads/${branch}`]);
77
+ assert(head() === expected && currentBranch() === branch && remoteBranchHead(url, branch) === expected, "Push changed local or remote HEAD; review the resulting commit before shipping.");
78
+ clean();
79
+ output({ branch, remote, headOid: expected, pushed: true }); return 0;
80
+ }
@@ -0,0 +1,117 @@
1
+ import { readFileSync } from "node:fs";
2
+ import { execFileSync, spawnSync } from "node:child_process";
3
+ import { loadConfig, type AgentToolConfig } from "../config";
4
+ import { validateCommitSubject } from "../pr/validateCommitSubject";
5
+ import { stripPrNumberSuffix } from "../pr/prNumberSuffix";
6
+ import { assert, git, option, flag, output } from "./core";
7
+ import { gitEnvironment } from "../git/environment";
8
+
9
+ export function signatureAccepted(status: string, policy: AgentToolConfig["commits"]["signatures"]): boolean {
10
+ return policy === "none" || (policy === "verified" ? ["G", "U"].includes(status) : ["G", "U", "E", "X", "Y", "R"].includes(status));
11
+ }
12
+
13
+ export function commitsCommand(args: string[]): number {
14
+ const action = args.shift();
15
+ const messageFile = option(args, "--message-file");
16
+ if (messageFile) {
17
+ assert(action === "check" && !args.length, "Usage: commits check --message-file <file>");
18
+ const config = loadConfig();
19
+ const message = readFileSync(messageFile, "utf8");
20
+ const trailers = execFileSync("git", ["interpret-trailers", "--parse"], { input: message, encoding: "utf8", env: gitEnvironment(), maxBuffer: 1024 * 1024 });
21
+ const errors: string[] = [];
22
+ if (config.commits.rejectCoauthors && /^co-authored-by:\s*\S/im.test(trailers)) errors.push("Co-authored-by trailer is forbidden.");
23
+ if (config.commits.rejectClaudeAttribution && /^(?:co-authored-by:.*(?:claude|anthropic)|.*generated.*(?:claude|anthropic))/im.test(message)) errors.push("Claude/Anthropic attribution is forbidden.");
24
+ if (config.commits.subjects) { try { validateCommitSubject(process.cwd(), stripPrNumberSuffix(message.split(/\r?\n/, 1)[0]!), { allowGenerated: true }); } catch (error) { errors.push((error as Error).message); } }
25
+ output({ ok: !errors.length, messageFile, errors }); return errors.length ? 1 : 0;
26
+ }
27
+ const range = option(args, "--range");
28
+ const excludes: string[] = [];
29
+ while (args.includes("--exclude")) { const index = args.indexOf("--exclude"); const value = args[index + 1]; assert(value && !value.startsWith("-"), "--exclude requires a revision."); excludes.push(value); args.splice(index, 2); }
30
+ const remote = option(args, "--exclude-remotes");
31
+ assert(!remote || /^[a-zA-Z0-9][a-zA-Z0-9._-]*$/.test(remote), "--exclude-remotes requires a named remote.");
32
+ assert(action === "check" && !!range && !range.startsWith("-") && !args.length, "Usage: commits check --range <revision-range>");
33
+ const config = loadConfig();
34
+ const commits = git(["rev-list", range, ...(excludes.length || remote ? ["--not", ...excludes, ...(remote ? [`--remotes=${remote}`] : [])] : []), "--"]).split("\n").filter(Boolean);
35
+ const findings: { commit: string; errors: string[] }[] = [];
36
+ for (const commit of commits) {
37
+ const errors: string[] = [];
38
+ if (config.commits.signatures !== "none") {
39
+ const status = git(["show", "--no-patch", "--format=%G?", commit]);
40
+ const headerFallback = config.commits.signatures === "present" && config.commits.signatureHeaderFallback && status === "N" && /^gpgsig(?:-sha256)? .+/m.test(git(["cat-file", "commit", commit]).split("\n\n", 1)[0]!);
41
+ if (!signatureAccepted(status, config.commits.signatures) && !headerFallback) errors.push(`Signature does not meet '${config.commits.signatures}' policy (${status}).`);
42
+ }
43
+ if (config.commits.rejectCoauthors && git(["show", "--no-patch", "--format=%(trailers:key=Co-authored-by,valueonly)", commit]).trim()) errors.push("Co-authored-by trailer is forbidden.");
44
+ if (config.commits.rejectClaudeAttribution && /^(?:co-authored-by:.*(?:claude|anthropic)|.*generated.*(?:claude|anthropic))/im.test(git(["show", "--no-patch", "--format=%B", commit]))) errors.push("Claude/Anthropic attribution is forbidden.");
45
+ if (config.commits.subjects) {
46
+ try { validateCommitSubject(process.cwd(), stripPrNumberSuffix(git(["show", "--no-patch", "--format=%s", commit])), { allowGenerated: true }); }
47
+ catch (error) { errors.push((error as Error).message); }
48
+ }
49
+ if (errors.length) findings.push({ commit, errors });
50
+ }
51
+ output({ ok: !findings.length, range, checked: commits.length, findings }); return findings.length ? 1 : 0;
52
+ }
53
+
54
+ /** Parse NUL-delimited --numstat; rename records carry an empty path then old/new. */
55
+ export function binaryPaths(source: string): string[] {
56
+ const records = source.split("\0");
57
+ const result: string[] = [];
58
+ for (let i = 0; i < records.length; i++) {
59
+ const record = records[i]!;
60
+ if (!record) continue;
61
+ const match = /^([^\t]+)\t([^\t]+)\t([\s\S]*)$/.exec(record);
62
+ assert(match, "Malformed Git numstat output.");
63
+ let file = match[3]!;
64
+ if (!file) { i++; file = records[++i]!; assert(!!file, "Incomplete rename record."); }
65
+ if (match[1] === "-" && match[2] === "-") result.push(file);
66
+ }
67
+ return result;
68
+ }
69
+
70
+ export function binariesCommand(args: string[]): number {
71
+ const staged = flag(args, "--staged");
72
+ const all = flag(args, "--all");
73
+ const upstream = flag(args, "--from-upstream");
74
+ const range = option(args, "--range");
75
+ assert(!args.length && [staged, all, upstream, !!range].filter(Boolean).length <= 1 && !range?.startsWith("-"), "Usage: checks binaries [--staged|--all|--range <range>|--from-upstream]");
76
+ let revisions = staged ? ["--cached"] : all ? ["--cached", git(["hash-object", "-t", "tree", "--stdin"])] : range ? [range] : [];
77
+ if (!revisions.length) {
78
+ const candidates = ["@{upstream}", ...(process.env.GITHUB_BASE_REF ? [`refs/remotes/origin/${process.env.GITHUB_BASE_REF}`] : []), "refs/remotes/origin/main", "refs/heads/main"];
79
+ const base = candidates.find(ref => spawnSync("git", ["rev-parse", "--verify", "--quiet", `${ref}^{commit}`], { stdio: "ignore" }).status === 0);
80
+ assert(base, "No upstream/base ref is available; pass --range explicitly."); revisions = [`${base}...HEAD`];
81
+ }
82
+ const files = binaryPaths(git(["diff", "--no-ext-diff", "--no-textconv", "--numstat", "-z", "--diff-filter=ACMR", ...revisions, "--"]));
83
+ const allowed = loadConfig().binaries.allow.map(pattern => new Bun.Glob(pattern));
84
+ const rejected = files.filter(file => !allowed.some(pattern => pattern.match(file)));
85
+ output({ ok: !rejected.length, binaries: files, rejected }); return rejected.length ? 1 : 0;
86
+ }
87
+
88
+ export interface GatePolicy { required?: string[]; allowSkipped?: string[]; conditional?: { job: string; source: string; output: string }[] }
89
+ export function evaluateGate(needs: unknown, policy: GatePolicy = {}): { ok: boolean; errors: string[] } {
90
+ assert(needs && typeof needs === "object" && !Array.isArray(needs), "Needs must be an object of GitHub job results.");
91
+ const entries = needs as Record<string, { result?: unknown; outputs?: Record<string, unknown> }>;
92
+ const errors: string[] = [];
93
+ if (!Object.keys(entries).length) errors.push("No dependency jobs were supplied.");
94
+ const conditional = new Map((policy.conditional ?? []).map(rule => [rule.job, rule]));
95
+ for (const name of new Set([...Object.keys(entries), ...(policy.required ?? []), ...conditional.keys()])) {
96
+ const item = entries[name];
97
+ const rule = conditional.get(name);
98
+ if (rule) {
99
+ const source = entries[rule.source];
100
+ const scope = source?.outputs?.[rule.output];
101
+ if (source?.result !== "success" || !["true", "false"].includes(String(scope)) || typeof scope !== "string") errors.push(`${name}: scope source ${rule.source}.${rule.output} must succeed and produce 'true' or 'false'.`);
102
+ else if (item?.result !== (scope === "true" ? "success" : "skipped")) errors.push(`${name}: expected ${scope === "true" ? "success" : "skipped"}.`);
103
+ } else if (item?.result !== "success" && !(item?.result === "skipped" && policy.allowSkipped?.includes(name) && !policy.required?.includes(name))) errors.push(`${name}: expected success, received ${String(item?.result)}.`);
104
+ }
105
+ return { ok: !errors.length, errors };
106
+ }
107
+
108
+ export function gateCommand(args: string[]): number {
109
+ const policyFile = option(args, "--policy");
110
+ assert(args.length === 1, "Usage: ci gate <needs.json|-> [--policy <policy.json>]");
111
+ const policy = policyFile ? JSON.parse(readFileSync(policyFile, "utf8")) as GatePolicy : {};
112
+ assert(policy && typeof policy === "object" && !Array.isArray(policy) && Object.keys(policy).every(key => ["required", "allowSkipped", "conditional"].includes(key)), "Invalid gate policy.");
113
+ for (const key of ["required", "allowSkipped"] as const) assert(policy[key] === undefined || (Array.isArray(policy[key]) && policy[key]!.every(value => typeof value === "string" && value.length)), `Invalid gate ${key}.`);
114
+ assert(policy.conditional === undefined || (Array.isArray(policy.conditional) && policy.conditional.every(rule => rule && Object.keys(rule).every(key => ["job", "source", "output"].includes(key)) && [rule.job, rule.source, rule.output].every(value => typeof value === "string" && value.length))), "Invalid conditional gate policy.");
115
+ const result = evaluateGate(JSON.parse(readFileSync(args[0] === "-" ? 0 : args[0]!, "utf8")), policy);
116
+ output(result); return result.ok ? 0 : 1;
117
+ }
@@ -0,0 +1,39 @@
1
+ export interface WorkflowConfig {
2
+ branch: { enforce: boolean; types: string[] | null; exempt: string[]; maxLength: number | null };
3
+ commits: { signatures: "none" | "present" | "verified"; signatureHeaderFallback: boolean; rejectCoauthors: boolean; rejectClaudeAttribution: boolean; subjects: boolean };
4
+ hooks: { files: { source: string; target: string; executable: boolean }[] };
5
+ binaries: { allow: string[] };
6
+ }
7
+
8
+ export const WORKFLOW_DEFAULTS: WorkflowConfig = {
9
+ branch: { enforce: false, types: null, exempt: ["main", "master"], maxLength: 72 },
10
+ commits: { signatures: "none", signatureHeaderFallback: false, rejectCoauthors: true, rejectClaudeAttribution: false, subjects: false },
11
+ hooks: { files: [] },
12
+ binaries: { allow: [] },
13
+ };
14
+
15
+ export function relativeFile(value: unknown): value is string {
16
+ return typeof value === "string" && value.length > 0 && !value.includes("\\") &&
17
+ !/[\x00-\x1f]/.test(value) && !value.split("/").some(part => !part || part === "." || part === "..");
18
+ }
19
+
20
+ export function validateWorkflowConfig(config: WorkflowConfig): void {
21
+ const fail = (name: string): never => { throw new Error(`Invalid config setting '${name}'.`); };
22
+ const strings = (value: unknown): value is string[] => Array.isArray(value) && value.every(item => typeof item === "string" && item.length > 0);
23
+ if (typeof config.branch.enforce !== "boolean") fail("branch.enforce");
24
+ if (config.branch.types !== null && (!strings(config.branch.types) || !config.branch.types.length || config.branch.types.some(type => !/^[a-z][a-z0-9-]*$/.test(type)))) fail("branch.types");
25
+ if (!strings(config.branch.exempt)) fail("branch.exempt");
26
+ if (config.branch.maxLength !== null && (!Number.isSafeInteger(config.branch.maxLength) || config.branch.maxLength < 1)) fail("branch.maxLength");
27
+ if (!["none", "present", "verified"].includes(config.commits.signatures)) fail("commits.signatures");
28
+ if (typeof config.commits.rejectCoauthors !== "boolean") fail("commits.rejectCoauthors");
29
+ if (typeof config.commits.subjects !== "boolean") fail("commits.subjects");
30
+ if (typeof config.commits.signatureHeaderFallback !== "boolean") fail("commits.signatureHeaderFallback");
31
+ if (typeof config.commits.rejectClaudeAttribution !== "boolean") fail("commits.rejectClaudeAttribution");
32
+ if (!Array.isArray(config.hooks.files)) fail("hooks.files");
33
+ const targets = new Set<string>();
34
+ for (const entry of config.hooks.files) {
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
+ targets.add(entry.target.toLowerCase());
37
+ }
38
+ if (!strings(config.binaries.allow) || config.binaries.allow.some(pattern => pattern.startsWith("/") || pattern.includes("..") || pattern.includes("\\"))) fail("binaries.allow");
39
+ }
@@ -0,0 +1,65 @@
1
+ import { execFileSync, spawnSync } from "node:child_process";
2
+ import { writeSync } from "node:fs";
3
+ import { gitEnvironment } from "../git/environment";
4
+
5
+ export function output(value: unknown): void { writeSync(1, `${JSON.stringify(value, null, 2)}\n`); }
6
+ export function assert(condition: unknown, message: string): asserts condition { if (!condition) throw new Error(message); }
7
+ export function oid(value: string): string { assert(/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/i.test(value), "Expected a full commit OID."); return value; }
8
+ export function read(command: string, args: string[], cwd = process.cwd()): string {
9
+ return execFileSync(command, args, { cwd, env: gitEnvironment(), encoding: "utf8", stdio: ["ignore", "pipe", "pipe"], maxBuffer: 64 * 1024 * 1024 }).trimEnd();
10
+ }
11
+ export function git(args: string[], cwd = process.cwd()): string { return read("git", args, cwd); }
12
+ export function json<T>(args: string[]): T { return JSON.parse(read("gh", args)) as T; }
13
+ /** Mutating Git commands deliberately retain normal hooks and their environment. */
14
+ export function mutateGit(args: string[]): void {
15
+ const result = spawnSync("git", args, { stdio: ["inherit", 2, 2], env: process.env });
16
+ if (result.error) throw result.error;
17
+ assert(result.status === 0, `git ${args[0]} failed (${result.signal ?? result.status}). Inspect checkout state before retrying.`);
18
+ }
19
+ export function clean(): void { assert(!git(["status", "--porcelain=v1", "--untracked-files=all"]), "Checkout has local changes; preserve them before continuing."); }
20
+ export function head(): string { return oid(git(["rev-parse", "HEAD"])); }
21
+ export function currentBranch(): string {
22
+ const branch = git(["branch", "--show-current"]);
23
+ assert(branch, "Detached HEAD; supply a branch name to checks or attach a branch before mutations.");
24
+ return branch;
25
+ }
26
+ export interface Repository { nameWithOwner: string; defaultBranchRef: { name: string }; url: string; sshUrl: string }
27
+ export function repository(): Repository {
28
+ const repo = json<Repository>(["repo", "view", "--json", "nameWithOwner,defaultBranchRef,url,sshUrl"]);
29
+ assert(/^[^/\s]+\/[^/\s]+$/.test(repo.nameWithOwner) && repo.defaultBranchRef?.name, "Could not resolve repository identity and default branch.");
30
+ return repo;
31
+ }
32
+ export function nativeBranch(name: string): boolean {
33
+ return !name.startsWith("-") && !name.includes("@{") && spawnSync("git", ["check-ref-format", "--branch", name], { stdio: "ignore", env: gitEnvironment() }).status === 0;
34
+ }
35
+ export function option(args: string[], name: string): string | undefined {
36
+ const index = args.indexOf(name);
37
+ if (index === -1) return undefined;
38
+ const value = args[index + 1];
39
+ assert(value && !value.startsWith("--"), `${name} requires a value.`);
40
+ args.splice(index, 2);
41
+ assert(!args.includes(name), `Duplicate ${name}.`);
42
+ return value;
43
+ }
44
+ export function flag(args: string[], name: string): boolean {
45
+ const index = args.indexOf(name);
46
+ if (index === -1) return false;
47
+ args.splice(index, 1);
48
+ assert(!args.includes(name), `Duplicate ${name}.`);
49
+ return true;
50
+ }
51
+ export function timeoutOptions(args: string[]): { timeoutMs: number; intervalMs: number } {
52
+ const seconds = Number(option(args, "--timeout") ?? "900");
53
+ const interval = Number(option(args, "--interval") ?? "10");
54
+ assert(Number.isFinite(seconds) && seconds >= 0 && seconds <= 86400 && Number.isFinite(interval) && interval >= 1 && interval <= 60, "Timeout must be 0–86400 seconds and interval 1–60 seconds.");
55
+ return { timeoutMs: seconds * 1000, intervalMs: interval * 1000 };
56
+ }
57
+ export async function poll<T>(inspect: () => { done: boolean; value: T } | Promise<{ done: boolean; value: T }>, options: { timeoutMs: number; intervalMs: number }): Promise<T> {
58
+ const deadline = Date.now() + options.timeoutMs;
59
+ while (true) {
60
+ const result = await inspect();
61
+ if (result.done) return result.value;
62
+ assert(Date.now() < deadline, `Timed out waiting: ${JSON.stringify(result.value)}`);
63
+ await new Promise(resolve => setTimeout(resolve, Math.min(options.intervalMs, deadline - Date.now())));
64
+ }
65
+ }
@@ -0,0 +1,112 @@
1
+ import { spawnSync } from "node:child_process";
2
+ import { createHash, randomUUID } from "node:crypto";
3
+ import { chmodSync, copyFileSync, existsSync, lstatSync, mkdirSync, readFileSync, readlinkSync, realpathSync, renameSync, symlinkSync, unlinkSync, writeFileSync } from "node:fs";
4
+ import path from "node:path";
5
+ import { loadConfig } from "../config";
6
+ import { assert, flag, git, output } from "./core";
7
+
8
+ const manifestName = ".agent-tool-hooks.json";
9
+ interface Manifest { schemaVersion: 1; files: Record<string, { hash: string; executable: boolean }> }
10
+ function digest(file: string): string { return createHash("sha256").update(readFileSync(file)).digest("hex"); }
11
+ function present(file: string): boolean { try { lstatSync(file); return true; } catch (error) { if ((error as NodeJS.ErrnoException).code === "ENOENT") return false; throw error; } }
12
+ function config(args: string[]): string | null {
13
+ // Do not use gitEnvironment(): it intentionally overrides hooksPath for reads.
14
+ const result = spawnSync("git", ["config", ...args], { encoding: "utf8" });
15
+ if (result.status === 1) return null;
16
+ assert(result.status === 0, "Could not read Git hook configuration.");
17
+ return result.stdout.trim();
18
+ }
19
+ function resolveDirectory(directory: string): string {
20
+ if (existsSync(directory)) return realpathSync(directory);
21
+ return path.join(resolveDirectory(path.dirname(directory)), path.basename(directory));
22
+ }
23
+ function within(parent: string, child: string): boolean { const relative = path.relative(parent, child); return !relative || (!relative.startsWith(`..${path.sep}`) && relative !== ".." && !path.isAbsolute(relative)); }
24
+
25
+ export function hooksCommand(args: string[]): number {
26
+ const action = args.shift();
27
+ const apply = flag(args, "--apply");
28
+ const adopt = flag(args, "--adopt");
29
+ assert((action === "install" || action === "check") && !args.length && (action === "install" || (!apply && !adopt)), "Usage: hooks install [--apply] [--adopt] | hooks check");
30
+ const root = realpathSync(git(["rev-parse", "--show-toplevel"]));
31
+ const common = resolveDirectory(git(["rev-parse", "--path-format=absolute", "--git-common-dir"]));
32
+ const worktreeConfig = config(["--local", "--bool", "--get", "extensions.worktreeConfig"]) === "true";
33
+ const local = (worktreeConfig ? config(["--worktree", "--type=path", "--get", "core.hooksPath"]) : null) ?? config(["--local", "--type=path", "--get", "core.hooksPath"]);
34
+ const inherited = config(["--type=path", "--get", "core.hooksPath"]);
35
+ const destination = resolveDirectory(local ? path.resolve(root, local) : path.join(common, "hooks"));
36
+ const effective = resolveDirectory(inherited ? path.resolve(root, inherited) : path.join(common, "hooks"));
37
+ const entries = loadConfig(root).hooks.files;
38
+ const sources = entries.map(entry => {
39
+ const source = path.join(root, entry.source);
40
+ assert(lstatSync(source).isFile() && realpathSync(source) === source, `Hook source must be a regular file without symlinks: ${entry.source}`);
41
+ git(["ls-files", "--error-unmatch", "--", entry.source]);
42
+ assert(!within(destination, source) && (path.dirname(source) === root || !within(path.dirname(source), destination)), "Hook destination overlaps source files.");
43
+ return { ...entry, source, hash: digest(source) };
44
+ });
45
+ // A configured destination inside the checkout must not contain tracked files.
46
+ if (within(root, destination)) assert(!git(["ls-files", "--", path.relative(root, destination)]), "Hook destination contains tracked files.");
47
+ const manifestFile = path.join(destination, manifestName);
48
+ if (!entries.length && !present(manifestFile)) { output({ ok: true, applied: false, destination, changes: [], blockers: [] }); return 0; }
49
+ let previous: Manifest = { schemaVersion: 1, files: {} };
50
+ if (present(manifestFile)) {
51
+ assert(lstatSync(manifestFile).isFile(), "Hook ownership manifest must be a regular file.");
52
+ previous = JSON.parse(readFileSync(manifestFile, "utf8"));
53
+ assert(previous.schemaVersion === 1 && previous.files && typeof previous.files === "object" && !Array.isArray(previous.files), "Invalid hook ownership manifest.");
54
+ for (const [name, entry] of Object.entries(previous.files)) assert(/^[a-zA-Z0-9][a-zA-Z0-9._-]*$/.test(name) && /^[a-f0-9]{64}$/.test(entry.hash) && typeof entry.executable === "boolean", "Invalid hook ownership entry.");
55
+ }
56
+ const changes: { target: string; status: string }[] = [];
57
+ const blockers: string[] = [];
58
+ const wanted = new Set(sources.map(source => source.target));
59
+ for (const source of sources) {
60
+ const file = path.join(destination, source.target);
61
+ const exists = present(file);
62
+ const regular = exists && lstatSync(file).isFile();
63
+ const owned = previous.files[source.target];
64
+ if (exists && !regular && !lstatSync(file).isSymbolicLink()) blockers.push(`${source.target}: destination is not a file or symlink.`);
65
+ if (exists && !owned && !adopt) blockers.push(`${source.target}: unmanaged file; inspect it, then use --adopt to back it up.`);
66
+ if (exists && owned && (!regular || digest(file) !== owned.hash)) blockers.push(`${source.target}: installed file was locally edited; preserve it before installing.`);
67
+ const matches = regular && digest(file) === source.hash && (!source.executable || !!(lstatSync(file).mode & 0o111));
68
+ changes.push({ target: source.target, status: matches && owned ? "unchanged" : exists ? "update" : "create" });
69
+ }
70
+ for (const [target, owned] of Object.entries(previous.files)) {
71
+ if (wanted.has(target)) continue;
72
+ const file = path.join(destination, target);
73
+ if (present(file) && (!lstatSync(file).isFile() || digest(file) !== owned.hash)) blockers.push(`${target}: stale managed file was edited; refusing removal.`);
74
+ changes.push({ target, status: "remove" });
75
+ }
76
+ const configure = destination !== effective;
77
+ const ok = !blockers.length && changes.every(change => change.status === "unchanged") && !configure;
78
+ if (action === "check" || !apply) {
79
+ output({ ok, applied: false, destination, configure, changes, blockers });
80
+ return action === "check" && !ok || blockers.length ? 1 : 0;
81
+ }
82
+ assert(!blockers.length, blockers.join("\n"));
83
+ mkdirSync(destination, { recursive: true });
84
+ const backupDirectory = path.join(destination, `.agent-tool-backup-${randomUUID()}`);
85
+ const backups: string[] = [];
86
+ // Preflight completes before changes. Never follow a destination symlink.
87
+ for (const change of changes.filter(change => change.status !== "unchanged")) {
88
+ const target = path.join(destination, change.target);
89
+ if (present(target)) {
90
+ mkdirSync(backupDirectory, { recursive: true, mode: 0o700 });
91
+ const backup = path.join(backupDirectory, change.target);
92
+ if (lstatSync(target).isSymbolicLink()) symlinkSync(readlinkSync(target), backup);
93
+ else copyFileSync(target, backup);
94
+ backups.push(backup);
95
+ }
96
+ if (change.status === "remove") { if (present(target)) unlinkSync(target); continue; }
97
+ const source = sources.find(source => source.target === change.target)!;
98
+ const temporary = path.join(destination, `.agent-tool-${randomUUID()}`);
99
+ copyFileSync(source.source, temporary);
100
+ assert(digest(temporary) === source.hash, `Hook source changed during installation: ${source.source}`);
101
+ chmodSync(temporary, source.executable ? 0o755 : 0o644);
102
+ renameSync(temporary, target);
103
+ }
104
+ const next: Manifest = { schemaVersion: 1, files: Object.fromEntries(sources.map(source => [source.target, { hash: source.hash, executable: source.executable }])) };
105
+ const temporary = path.join(destination, `.agent-tool-manifest-${randomUUID()}`);
106
+ writeFileSync(temporary, `${JSON.stringify(next, null, 2)}\n`, { mode: 0o600, flag: "wx" });
107
+ renameSync(temporary, manifestFile);
108
+ if (configure) assert(spawnSync("git", ["config", "--local", "core.hooksPath", destination], { stdio: "inherit" }).status === 0, "Could not configure installed hooks.");
109
+ const after = config(["--type=path", "--get", "core.hooksPath"]);
110
+ assert(resolveDirectory(after ? path.resolve(root, after) : path.join(common, "hooks")) === destination, "Effective hooksPath does not match installation; inspect Git configuration.");
111
+ output({ ok: true, applied: true, destination, changes, backups }); return 0;
112
+ }