@a2f0/agent-tool 0.1.58 → 0.1.59

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 CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@a2f0/agent-tool",
3
- "version": "0.1.58",
3
+ "version": "0.1.59",
4
4
  "packageManager": "bun@1.4.4",
5
5
  "type": "module",
6
6
  "description": "Portable cross-agent review, PR workflows, and shared skills",
@@ -54,6 +54,9 @@ until the next review completes. Preserve unrelated work.
54
54
 
55
55
  Before reporting success, confirm HEAD still matches the reviewed commit and
56
56
  that an existing PR points to that same commit. If the base moved, refresh it and
57
- review again before shipping. Report reviewer, exact base and head IDs, verdict,
58
- remaining findings, validation, and any repairs performed. This skill does not
59
- authorize pushing, opening a PR, or merging unless the user requested that work.
57
+ review again before shipping, unless the new HEAD only integrated the base and
58
+ prepared versions and `agent-tool review carry <reviewed-head> <new-head>`
59
+ accepts it; then report the review as carried, with both heads. Report
60
+ reviewer, exact base and head IDs, verdict, remaining findings, validation, and
61
+ any repairs performed. This skill does not authorize pushing, opening a PR, or
62
+ merging unless the user requested that work.
@@ -65,7 +65,15 @@ command, so they can be found and stopped.
65
65
  `agent-tool versions resolve-conflicts` resolves conflicts confined to
66
66
  version fields. Review the resulting committed HEAD with an independent
67
67
  reviewer using the bundled cross-agent-review skill. Repair blocking findings
68
- and review every changed HEAD again. Review failure blocks shipping.
68
+ and review every changed HEAD again. Review failure blocks shipping. One
69
+ change keeps a review: after a clean review, a new HEAD that only integrated
70
+ the base and prepared versions (as when another PR took the same version
71
+ first). When `agent-tool review carry <reviewed-head> <new-head>` exits 0
72
+ with `ok: true`, the earlier clean review stands, and the new HEAD is the
73
+ reviewed head from then on; report the review as carried, giving the
74
+ reviewed head and the command's JSON output. Every other changed HEAD,
75
+ including one the command rejects, gets an independent review, and CI
76
+ still runs on the new HEAD.
69
77
  4. Run `agent-tool branch push <reviewed-head> --remote <remote>` through
70
78
  normal hooks; it verifies local and remote identity afterward. If a hook
71
79
  changed content or HEAD, review that result.
@@ -84,7 +92,8 @@ command, so they can be found and stopped.
84
92
  sets `merge.requireStrictBaseFreshness`; under that policy the wait stops
85
93
  early, so cancel the stale head's CI with
86
94
  `agent-tool pr cancel-runs --head <reviewed-head>`, then integrate,
87
- validate, review, push, and wait again. Then run
95
+ validate, review (or carry the review, as in step 3), push, and wait again.
96
+ Then run
88
97
  `agent-tool pr preflight <reviewed-head> <base-branch> <reviewed-base>` to
89
98
  recheck CI, conflicts, the live base, PR identity, local state, and explicit
90
99
  version policy. When versions are managed,
@@ -120,9 +129,9 @@ untracked process it started, and remove worktrees it added. Report what
120
129
  remains and why; the work is not done while teardown fails for anything it
121
130
  started.
122
131
 
123
- Never infer a clean review from process success alone or carry a review across
124
- content changes. Do not weaken configured CI policy to get a merge through.
125
- If a step fails, preserve useful intermediate work and report the concrete
132
+ Never infer a clean review from process success alone, or carry a review to a
133
+ HEAD that `review carry` does not accept. Do not weaken configured CI policy to
134
+ get a merge through. If a step fails, preserve useful intermediate work and report the concrete
126
135
  remaining issue. Report PR link, merged commit, review verdict, validation, final
127
136
  checkout state, the base's health at the start and end and anything repaired or
128
137
  hardened, the teardown result, and whether the shipped local branch was pruned
@@ -25,8 +25,10 @@ before merging. It checks local and PR identity, that the head contains the
25
25
  reviewed base, conflicts and merge readiness, explicit version policy against
26
26
  the live base, configured strict rulesets, and passing checks; under the strict
27
27
  policy the live base must also equal the reviewed one. If an identity changed,
28
- refresh, integrate, validate, and review again. Read unresolved feedback with
29
- `pr threads list` and follow project review policy.
28
+ refresh, integrate, validate, and review again; a new HEAD that
29
+ `agent-tool review carry <reviewed-head> <new-head>` accepts keeps the earlier
30
+ clean review. Read unresolved feedback with `pr threads list` and follow
31
+ project review policy.
30
32
 
31
33
  Use a title that satisfies `agent-tool.json` and pass both reviewed HEAD and
32
34
  base branch:
package/src/cli.ts CHANGED
@@ -8,6 +8,7 @@ import { checkGraph } from "./graph/check";
8
8
  import { stateMachinesCommand } from "./stateMachines/command";
9
9
  import { buildScreenshots, describeScreenshots } from "./screenshots/build";
10
10
  import { review } from "./harnesses";
11
+ import { carryReviewCommand } from "./review/carry";
11
12
  import { runAgentToolAction } from "./runAgentToolAction";
12
13
  import { BUNDLED_SKILLS } from "./skills/bundled";
13
14
  import { checkSkills, installSkills } from "./skills/install";
@@ -48,7 +49,7 @@ Usage: agent-tool [--repo <directory>] [--config <file>] <command>
48
49
  commits check --message-file <file> Commit-msg attribution and subject policy
49
50
  checks binaries [--staged|--all|--range range|--from-upstream]
50
51
  hooks install [--apply] [--adopt] | check
51
- push-gate hook | check Canonical pre-push body; static check of the declared gate
52
+ push-gate hook | check Canonical pre-push body; static check: no tests, builds, or installs
52
53
  push-gate run --pre-push <remote> <url> Built-in guards, then pushGate steps (the pre-push body)
53
54
  repo context [--fetch] | cleanup <PR> <shipped-head> [--apply] [--keep-branch]
54
55
  repo base-health [--branch name] [--limit N] CI health of the default branch's tip (GitHub only)
@@ -58,6 +59,7 @@ Usage: agent-tool [--repo <directory>] [--config <file>] <command>
58
59
  release verify <package> <version> <merge-oid> --workflow name [--timeout seconds]
59
60
  logs <file> [--max-bytes N] [--tail-lines N] Bounded local log tail
60
61
  review <claude|codex|opencode> [effort] [--base <local-ref>]
62
+ review carry <reviewed-head> <new-head> [--base <ref>] Whether a clean review covers a base-merge and versions-only head
61
63
  pr open [title] [--body-file file] Body from the file or stdin; branch already pushed
62
64
  pr merge <subject-or-empty> <head-oid> <base-branch>
63
65
  pr context | checks [--wait] [--head oid] [--allow-behind] [--timeout seconds]
@@ -237,6 +239,7 @@ export function main(argv = process.argv.slice(2)): number | Promise<number> {
237
239
  if (command === "run-group") return runGroup(args);
238
240
  if (command === "runs") return listRuns(args);
239
241
  if (command === "checks") { usage(args.shift() === "binaries", "Usage: checks binaries [--staged|--all|--range range|--from-upstream]"); return binariesCommand(args); }
242
+ if (command === "review" && args[0] === "carry") return carryReviewCommand(root, args.slice(1));
240
243
  if (command === "review") {
241
244
  const name = args.shift(); usage(!!name, "Usage: agent-tool review <claude|codex|opencode> [effort] [--base ref]");
242
245
  let effort: string | undefined, base: string | undefined;
@@ -1,6 +1,6 @@
1
1
  import { createHash, randomUUID } from "node:crypto";
2
- import { execFileSync } from "node:child_process";
3
- import { existsSync, lstatSync, mkdirSync, readFileSync, readdirSync, readlinkSync, renameSync, writeFileSync } from "node:fs";
2
+ import { execFileSync, spawnSync } from "node:child_process";
3
+ import { existsSync, lstatSync, mkdirSync, readFileSync, readdirSync, readlinkSync, realpathSync, renameSync, writeFileSync } from "node:fs";
4
4
  import { constants } from "node:os";
5
5
  import path from "node:path";
6
6
  import { FORWARDED_SIGNALS, runCommand, type RunReceipt } from "./run";
@@ -11,17 +11,51 @@ export interface SourceState { headOid: string; treeOid: string; branch: string
11
11
  export function sourceState(): SourceState {
12
12
  const hash = createHash("sha256");
13
13
  const add = (value: string | Buffer) => { hash.update(String(Buffer.byteLength(value))); hash.update(":" ); hash.update(value); };
14
- const rawDiff = (args: string[]) => execFileSync("git", ["diff", "--no-ext-diff", "--no-textconv", "--binary", ...args, "--"], { env: gitEnvironment(), maxBuffer: 64 * 1024 * 1024, stdio: ["ignore", "pipe", "pipe"] });
15
- add(rawDiff(["HEAD"])); add(rawDiff(["--cached"]));
16
- for (const record of git(["status", "--porcelain=v2", "--ignore-submodules=none", "-z"]).split("\0")) {
14
+ fingerprintCheckout(add, process.cwd(), "", gitEnvironment(), ["HEAD"]);
15
+ return { headOid: head(), treeOid: git(["rev-parse", "HEAD^{tree}"]), branch: git(["branch", "--show-current"]) || null, fingerprint: hash.digest("hex") };
16
+ }
17
+
18
+ /** Where Git finds a repository; a hook may export them, and a nested repository's reads must find its own. */
19
+ const GIT_LOCATION = ["GIT_DIR", "GIT_WORK_TREE", "GIT_INDEX_FILE", "GIT_OBJECT_DIRECTORY", "GIT_ALTERNATE_OBJECT_DIRECTORIES", "GIT_COMMON_DIR", "GIT_PREFIX", "GIT_IMPLICIT_WORK_TREE", "GIT_GRAFT_FILE", "GIT_SHALLOW_FILE", "GIT_REPLACE_REF_BASE"];
20
+
21
+ /**
22
+ * Hash a checkout's tracked changes (against `diffBase`), its staged changes,
23
+ * and its nonignored untracked files, naming each file with `prefix`. Git lists
24
+ * an untracked nested repository as one `dir/` entry without descending into
25
+ * it; that repository is hashed the same way from its own root, after its HEAD
26
+ * (or `unborn`), so a commit, edit, or new file inside it changes the result.
27
+ */
28
+ function fingerprintCheckout(add: (value: string | Buffer) => void, cwd: string, prefix: string, env: NodeJS.ProcessEnv, diffBase: string[]): void {
29
+ const read = (args: string[]) => execFileSync("git", args, { cwd, env, maxBuffer: 64 * 1024 * 1024, stdio: ["ignore", "pipe", "pipe"] });
30
+ const rawDiff = (args: string[]) => read(["diff", "--no-ext-diff", "--no-textconv", "--binary", ...args, "--"]);
31
+ add(rawDiff(diffBase)); add(rawDiff(["--cached"]));
32
+ for (const record of read(["status", "--porcelain=v2", "--ignore-submodules=none", "-z"]).toString("utf8").split("\0")) {
17
33
  if (/^[12] /.test(record)) { const submodule = record.split(" ")[2]!; assert(!submodule.startsWith("S") || submodule === "S...", "Dirty submodules cannot be fingerprinted; validate from a clean submodule state."); }
18
34
  }
19
- for (const file of git(["ls-files", "--others", "--exclude-standard", "-z"]).split("\0").filter(Boolean).sort()) {
20
- add(file); const stat = lstatSync(file); add(String(stat.mode));
21
- if (stat.isSymbolicLink()) add(readlinkSync(file));
22
- else { assert(stat.isFile(), `Cannot fingerprint non-file '${file}'.`); add(readFileSync(file)); }
35
+ let nestedEnv: NodeJS.ProcessEnv | undefined;
36
+ for (const file of read(["ls-files", "--others", "--exclude-standard", "-z"]).toString("utf8").split("\0").filter(Boolean).sort()) {
37
+ const full = path.join(cwd, file);
38
+ add(prefix + file); const stat = lstatSync(full); add(String(stat.mode));
39
+ if (stat.isSymbolicLink()) add(readlinkSync(full));
40
+ else if (stat.isFile()) add(readFileSync(full));
41
+ else {
42
+ nestedEnv ??= Object.fromEntries(Object.entries(env).filter(([name]) => !GIT_LOCATION.includes(name)));
43
+ const headOid = stat.isDirectory() && file.endsWith("/") ? nestedHead(full, nestedEnv) : undefined;
44
+ assert(headOid !== undefined, `Cannot fingerprint non-file '${prefix + file}'.`);
45
+ add(headOid ?? "unborn");
46
+ // Without a commit there is no HEAD to diff against; the index stands in for it.
47
+ fingerprintCheckout(add, full, prefix + file, nestedEnv, headOid === null ? [] : ["HEAD"]);
48
+ }
23
49
  }
24
- return { headOid: head(), treeOid: git(["rev-parse", "HEAD^{tree}"]), branch: git(["branch", "--show-current"]) || null, fingerprint: hash.digest("hex") };
50
+ }
51
+
52
+ /** The HEAD commit of the repository rooted at `directory` (null when unborn), or undefined when Git does not see one there. */
53
+ function nestedHead(directory: string, env: NodeJS.ProcessEnv): string | null | undefined {
54
+ const top = spawnSync("git", ["rev-parse", "--show-toplevel"], { cwd: directory, env, encoding: "utf8", stdio: ["ignore", "pipe", "ignore"] });
55
+ // A `.git` Git cannot open makes it resolve the enclosing repository instead.
56
+ if (top.status !== 0 || realpathSync(top.stdout.trim()) !== realpathSync(directory)) return undefined;
57
+ const resolved = spawnSync("git", ["rev-parse", "--verify", "--quiet", "HEAD^{commit}"], { cwd: directory, env, encoding: "utf8", stdio: ["ignore", "pipe", "ignore"] });
58
+ return resolved.status === 0 ? resolved.stdout.trim() : null;
25
59
  }
26
60
 
27
61
  function reportsDirectory(): string { return path.join(git(["rev-parse", "--path-format=absolute", "--git-common-dir"]), "agent-tool", "runs"); }
@@ -19,7 +19,7 @@ export type Decision = "allow" | "ask";
19
19
  export interface CatalogEntry { command: string; class: PermissionClass; applyClass?: PermissionClass }
20
20
 
21
21
  export const CATALOG: CatalogEntry[] = [
22
- ...["--help", "--version", "logs", "runs list", "doctor", "config show", "branch check", "branch status", "commits check", "checks binaries", "repo context", "policy check", "toolchain check", "ci gate", "release plan", "release verify", "pr context", "pr checks", "pr logs", "pr preflight", "pr threads list", "versions plan", "versions check", "dependencies check-terraform-plan", "dependencies diff", "skills list", "skills check", "hooks check", "push-gate hook", "push-gate check", "repo base-health", "images list", "graph check", "state-machines", "permissions show", "permissions check", "proc list"]
22
+ ...["--help", "--version", "logs", "runs list", "doctor", "config show", "branch check", "branch status", "commits check", "checks binaries", "repo context", "policy check", "toolchain check", "ci gate", "release plan", "release verify", "pr context", "pr checks", "pr logs", "pr preflight", "pr threads list", "versions plan", "versions check", "dependencies check-terraform-plan", "dependencies diff", "skills list", "skills check", "hooks check", "push-gate hook", "push-gate check", "repo base-health", "review carry", "images list", "graph check", "state-machines", "permissions show", "permissions check", "proc list"]
23
23
  .map(command => ({ command, class: "read" as const })),
24
24
  ...["bun install", "bun update", "bun remove", "bun test", "branch create", "versions bump", "versions prepare", "versions resolve-conflicts", "images build", "screenshots build", "review", "init", "proc stop"]
25
25
  .map(command => ({ command, class: "local" as const })),
@@ -0,0 +1,203 @@
1
+ import { execFileSync, spawnSync } from "node:child_process";
2
+ import { loadConfig } from "../config";
3
+ import { viewCurrentBranchPr } from "../git/currentBranchPr";
4
+ import { gitEnvironment } from "../git/environment";
5
+ import { resolveFreshBaseRef } from "../git/prContext";
6
+ import { assert, git as readGit, option, output, repository } from "../workflows/core";
7
+ import { planVersions } from "../version/bumpVersions";
8
+ import { manifestPath, readVersion, withVersion, workspacePackages } from "../version/packageVersion";
9
+ import { mergeManifestIgnoringVersion } from "../version/resolveVersionConflicts";
10
+
11
+ /**
12
+ * One commit between the reviewed head and the new head: a merge of the base
13
+ * branch, a version-only commit, or anything else, which always fails.
14
+ */
15
+ export interface CarryStep { commit: string; kind: "base-merge" | "versions" | "other"; ok: boolean; paths: string[]; reason: string | null }
16
+ export interface CarryReport { ok: boolean; reviewedHead: string; head: string; base: { ref: string; oid: string }; steps: CarryStep[]; reasons: string[] }
17
+
18
+ const FULL_OID = /^(?:[a-f0-9]{40}|[a-f0-9]{64})$/;
19
+
20
+ function gitReader(root: string) {
21
+ const env = gitEnvironment();
22
+ const read = (args: string[]) => execFileSync("git", args, { cwd: root, env, encoding: "utf8", maxBuffer: 256 * 1024 * 1024, stdio: ["ignore", "pipe", "pipe"] });
23
+ const succeeds = (args: string[]) => spawnSync("git", args, { cwd: root, env, stdio: "ignore" }).status === 0;
24
+ const blob = (commit: string, file: string): string | null => {
25
+ const result = spawnSync("git", ["show", `${commit}:${file}`], { cwd: root, env, encoding: "utf8", maxBuffer: 256 * 1024 * 1024, stdio: ["ignore", "pipe", "ignore"] });
26
+ return result.status === 0 ? result.stdout : null;
27
+ };
28
+ return { read, succeeds, blob, env };
29
+ }
30
+ type Git = ReturnType<typeof gitReader>;
31
+
32
+ /**
33
+ * Whether `head` differs from a clean-reviewed `reviewedHead` only by
34
+ * integrating the base and preparing versions, so the review still stands.
35
+ * Walking the first-parent history from the reviewed head, every commit must
36
+ * be either a merge whose other parent the base already contains and whose
37
+ * tree is Git's own merge of its parents (conflicts allowed only in versioned
38
+ * manifests, resolved exactly as `versions resolve-conflicts` resolves them),
39
+ * or a commit that changes only the version fields of versioned manifests and
40
+ * the lockfile's workspace versions, setting every package to the version
41
+ * `versions prepare` targets on its parent. Read-only, and runs no repository
42
+ * code: custom merge drivers are disabled.
43
+ */
44
+ export function carryReview(root: string, reviewedHead: string, head: string, base: { ref: string; oid: string }): CarryReport {
45
+ const git = gitReader(root);
46
+ const report = (steps: CarryStep[], reasons: string[]): CarryReport => {
47
+ const all = [...reasons, ...steps.flatMap(step => step.reason ? [`${step.commit}: ${step.reason}`] : [])];
48
+ return { ok: !all.length, reviewedHead, head, base, steps, reasons: all };
49
+ };
50
+ for (const [name, value] of [["reviewed head", reviewedHead], ["new head", head], ["base", base.oid]] as const) {
51
+ if (!FULL_OID.test(value) || !git.succeeds(["cat-file", "-e", `${value}^{commit}`])) return report([], [`The ${name} ${value} is not a commit in this clone.`]);
52
+ }
53
+ if (!git.succeeds(["merge-base", "--is-ancestor", reviewedHead, head])) return report([], ["The new head does not descend from the reviewed head, so its history was rewritten (for example by a rebase)."]);
54
+ const chain = git.read(["rev-list", "--first-parent", "--reverse", `${reviewedHead}..${head}`]).split("\n").filter(Boolean);
55
+ if (!chain.length) return report([], []);
56
+ const parents = new Map(git.read(["log", "--no-walk=unsorted", "--format=%H %P", ...chain]).split("\n").filter(Boolean).map(line => { const [commit, ...rest] = line.split(" "); return [commit!, rest]; }));
57
+ // Each commit must build on the one before it, starting from the reviewed head itself.
58
+ let previous = reviewedHead;
59
+ for (const commit of chain) {
60
+ if (parents.get(commit)?.[0] !== previous) return report([], [`The reviewed head is not on the new head's first-parent history (${commit} does not build on ${previous}).`]);
61
+ previous = commit;
62
+ }
63
+ const steps = chain.map((commit): CarryStep => {
64
+ const list = parents.get(commit)!;
65
+ try {
66
+ if (list.length === 2) return baseMerge(root, git, commit, list[0]!, list[1]!, base);
67
+ if (list.length === 1) return versionCommit(root, git, commit, list[0]!, base.oid);
68
+ return { commit, kind: "other", ok: false, paths: [], reason: `merges ${list.length} parents at once.` };
69
+ } catch (error) { return { commit, kind: list.length === 2 ? "base-merge" : list.length === 1 ? "versions" : "other", ok: false, paths: [], reason: `could not be checked: ${(error as Error).message}` }; }
70
+ });
71
+ return report(steps, []);
72
+ }
73
+
74
+ /**
75
+ * `review carry <reviewed-head> <new-head> [--base <ref>]`. Without `--base`,
76
+ * the base is the PR's base branch (the default branch when no PR exists),
77
+ * fetched fresh from GitHub as `repo context --fetch` does. Exits 1 unless the
78
+ * review carries.
79
+ */
80
+ export function carryReviewCommand(root: string, args: string[]): number {
81
+ const given = option(args, "--base");
82
+ assert(args.length === 2 && args.every(value => FULL_OID.test(value)), "Usage: agent-tool review carry <reviewed-head-oid> <new-head-oid> [--base <ref>]");
83
+ let base: { ref: string; oid: string };
84
+ if (given !== undefined) {
85
+ assert(!given.startsWith("-"), "--base requires a ref.");
86
+ base = { ref: given, oid: readGit(["rev-parse", "--verify", "--end-of-options", `${given}^{commit}`]) };
87
+ } else {
88
+ const repo = repository();
89
+ const branch = readGit(["branch", "--show-current"]) || null;
90
+ const pr = branch ? viewCurrentBranchPr(branch) : undefined;
91
+ const baseRepo = pr?.repo ?? repo.nameWithOwner, baseBranch = pr?.baseRefName ?? repo.defaultBranchRef.name;
92
+ base = { ref: `${baseRepo} ${baseBranch}`, oid: resolveFreshBaseRef(baseRepo, baseBranch) };
93
+ }
94
+ const result = carryReview(root, args[0]!, args[1]!, base);
95
+ output(result);
96
+ return result.ok ? 0 : 1;
97
+ }
98
+
99
+ function baseMerge(root: string, git: Git, commit: string, ours: string, theirs: string, base: { ref: string; oid: string }): CarryStep {
100
+ const step = (ok: boolean, paths: string[], reason: string | null): CarryStep => ({ commit, kind: "base-merge", ok, paths, reason });
101
+ if (!git.succeeds(["merge-base", "--is-ancestor", theirs, base.oid])) return step(false, [], `merges ${theirs}, which ${base.ref} (${base.oid}) does not contain.`);
102
+ const merged = spawnSync("git", [...inertMergeOptions(root, git.env), "merge-tree", "--write-tree", "-z", "--no-messages", ours, theirs], { cwd: root, env: git.env, encoding: "utf8", maxBuffer: 256 * 1024 * 1024, stdio: ["ignore", "pipe", "pipe"] });
103
+ if (merged.status !== 0 && merged.status !== 1) throw new Error(`git merge-tree failed: ${merged.stderr.trim()}`);
104
+ const [tree, ...entries] = merged.stdout.split("\0").filter(Boolean);
105
+ // Conflict entries are `<mode> <object> <stage>\t<path>`, one per stage present.
106
+ const stages = new Map<string, Map<string, string>>();
107
+ for (const entry of entries) {
108
+ const match = /^(\d+) ([a-f0-9]+) ([123])\t(.*)$/s.exec(entry);
109
+ if (!match) throw new Error(`unexpected git merge-tree output '${entry}'`);
110
+ stages.set(match[4]!, (stages.get(match[4]!) ?? new Map()).set(match[3]!, match[2]!));
111
+ }
112
+ const conflicted = [...stages.keys()].sort();
113
+ const differing = git.read(["diff-tree", "-r", "--no-renames", "--name-only", "-z", tree!, `${commit}^{tree}`]).split("\0").filter(Boolean);
114
+ if (!conflicted.length) return differing.length ? step(false, [], `differs from Git's own merge of its parents in ${differing.join(", ")}.`) : step(true, [], null);
115
+ // Like `versions resolve-conflicts`, which ran with the branch checked out.
116
+ const manifests = new Set(workspacePackages(root, ours).map(manifestPath));
117
+ const manual = conflicted.filter(file => !manifests.has(file));
118
+ if (manual.length) return step(false, conflicted, `resolves conflicts outside the versioned manifests by hand: ${manual.join(", ")}.`);
119
+ const extra = differing.filter(file => !stages.has(file));
120
+ if (extra.length) return step(false, conflicted, `differs from Git's own merge of its parents in ${extra.join(", ")}.`);
121
+ for (const file of conflicted) {
122
+ const sides = stages.get(file)!;
123
+ if (sides.size !== 3) return step(false, conflicted, `has a conflict in ${file} that is not a content conflict, which versions resolve-conflicts does not resolve.`);
124
+ const content = (stage: string) => git.read(["cat-file", "blob", sides.get(stage)!]);
125
+ const resolved = mergeManifestIgnoringVersion(root, content("1"), content("2"), content("3"));
126
+ if (resolved === null) return step(false, conflicted, `${file} conflicts beyond its version field.`);
127
+ const mode = (treeish: string) => git.read(["ls-tree", "-z", treeish, "--", file]).split(" ", 1)[0];
128
+ if (git.blob(commit, file) !== resolved || mode(commit) !== mode(tree!)) return step(false, conflicted, `resolves ${file} differently from versions resolve-conflicts.`);
129
+ }
130
+ return step(true, conflicted, null);
131
+ }
132
+
133
+ /**
134
+ * `git -c` options that keep `git merge-tree` from running programs any
135
+ * configuration names, so this read-only check executes no repository code:
136
+ * every custom merge driver becomes the shell's `false`, so its paths conflict
137
+ * instead, and renormalization, which would run clean filters, is off. Options
138
+ * on the command line come last, after the repository's files and any
139
+ * inherited `GIT_CONFIG_PARAMETERS` or `GIT_CONFIG_COUNT`, so they win. A merge
140
+ * that relied on a driver then needs a new review.
141
+ */
142
+ function inertMergeOptions(root: string, env: NodeJS.ProcessEnv): string[] {
143
+ const listed = spawnSync("git", ["config", "-z", "--get-regexp", "^merge\\..+\\.driver$"], { cwd: root, env, encoding: "utf8", stdio: ["ignore", "pipe", "pipe"] });
144
+ // Exit 1 means no driver is configured.
145
+ if (listed.status !== 0 && listed.status !== 1) throw new Error(`git config failed: ${listed.stderr.trim()}`);
146
+ const drivers = listed.status === 0 ? listed.stdout.split("\0").filter(Boolean).map(entry => entry.split("\n", 1)[0]!) : [];
147
+ // `-c` splits at the first `=`, so a driver whose name holds one cannot be overridden.
148
+ const unsafe = drivers.filter(driver => driver.includes("="));
149
+ if (unsafe.length) throw new Error(`cannot disable the merge driver ${unsafe.join(", ")}`);
150
+ return [...drivers.flatMap(driver => ["-c", `${driver}=false`]), "-c", "merge.renormalize=false"];
151
+ }
152
+
153
+ const deepEqual = (left: unknown, right: unknown) => Bun.deepEquals(left, right, true);
154
+ function lockWithoutVersions(source: string): { lock: unknown; versions: Map<string, unknown> } {
155
+ const lock = Bun.JSONC.parse(source) as { workspaces?: Record<string, Record<string, unknown>> } | null;
156
+ const versions = new Map<string, unknown>();
157
+ for (const [directory, workspace] of Object.entries(lock?.workspaces ?? {})) {
158
+ if (workspace && typeof workspace === "object" && "version" in workspace) { versions.set(directory, workspace.version); delete workspace.version; }
159
+ }
160
+ return { lock, versions };
161
+ }
162
+
163
+ function versionCommit(root: string, git: Git, commit: string, parent: string, baseOid: string): CarryStep {
164
+ const changes = git.read(["diff-tree", "-r", "--no-renames", "-z", parent, commit]).split("\0").filter(Boolean);
165
+ const paths: string[] = [];
166
+ const step = (ok: boolean, reason: string | null): CarryStep => ({ commit, kind: "versions", ok, paths, reason });
167
+ const manifests = new Set(workspacePackages(root, commit).map(manifestPath));
168
+ const lockfile = loadConfig(root).versions.lockfile;
169
+ // Raw entries alternate `:<old mode> <new mode> <old oid> <new oid> <status>` and the path.
170
+ for (let index = 0; index < changes.length; index += 2) {
171
+ const [oldMode, newMode, , , status] = changes[index]!.slice(1).split(" ");
172
+ const file = changes[index + 1]!;
173
+ paths.push(file);
174
+ if (status !== "M" || oldMode !== newMode || (!manifests.has(file) && file !== lockfile)) return step(false, `changes ${file}, which is not a version field.`);
175
+ }
176
+ for (const file of paths.filter(file => manifests.has(file))) {
177
+ const before = git.blob(parent, file)!, after = git.blob(commit, file)!;
178
+ if (withVersion(before, readVersion(after)) !== after) return step(false, `changes ${file} beyond its version field.`);
179
+ }
180
+ if (lockfile) {
181
+ const before = lockWithoutVersions(git.blob(parent, lockfile) ?? "{}"), after = lockWithoutVersions(git.blob(commit, lockfile) ?? "{}");
182
+ if (!deepEqual(before.lock, after.lock)) return step(false, `changes ${lockfile} beyond its workspace versions.`);
183
+ // Every bumped workspace, and every workspace whose recorded version moved, must record its manifest's version.
184
+ // Bun does not record the root package's version.
185
+ const directories = new Set([
186
+ ...paths.filter(file => manifests.has(file) && file !== "package.json").map(file => file.slice(0, -"/package.json".length)),
187
+ ...[...new Set([...before.versions.keys(), ...after.versions.keys()])].filter(directory => before.versions.get(directory) !== after.versions.get(directory)),
188
+ ]);
189
+ for (const directory of [...directories].sort()) {
190
+ const source = git.blob(commit, directory ? `${directory}/package.json` : "package.json");
191
+ if (source === null || after.versions.get(directory) !== readVersion(source)) return step(false, `leaves ${lockfile} recording another version of ${directory || "."} than its manifest.`);
192
+ }
193
+ }
194
+ // `versions prepare` ran on the parent against the newest base commit it contains, and sets each package to its
195
+ // target there. Planned from the parent, so a new major or minor version in this commit is never its own target.
196
+ const integrated = git.read(["merge-base", parent, baseOid]).trim();
197
+ const plans = new Map(planVersions(root, integrated, parent).map(plan => [plan.manifest, plan]));
198
+ const unplanned = paths.filter(file => manifests.has(file) && !plans.has(file));
199
+ if (unplanned.length) return step(false, `changes the version of ${unplanned.join(", ")}, which versions prepare does not set.`);
200
+ const wrong = [...plans.values()].map(plan => ({ plan, version: readVersion(git.blob(commit, plan.manifest)!) })).filter(({ plan, version }) => version !== plan.targetVersion);
201
+ if (wrong.length) return step(false, `leaves ${wrong.map(({ plan, version }) => `${plan.manifest} at ${version}, not ${plan.targetVersion}`).join(", ")}, which versions prepare against ${integrated} would not.`);
202
+ return step(true, null);
203
+ }
@@ -1,12 +1,12 @@
1
1
  // Generated by scripts/build/bundle-skills.ts; edit skills/*/SKILL.md and skills/*/references/*.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 an independent reviewer using a different model/provider from the author\nwhen possible, not merely a different CLI: Hermes and OpenCode can use the same\nmodel as another harness. Hermes can coordinate this skill but is not a `review`\nadapter. Honor a requested reviewer or effort; otherwise use an available\nindependent 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",
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 an independent reviewer using a different model/provider from the author\nwhen possible, not merely a different CLI: Hermes and OpenCode can use the same\nmodel as another harness. Hermes can coordinate this skill but is not a `review`\nadapter. Honor a requested reviewer or effort; otherwise use an available\nindependent 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, unless the new HEAD only integrated the base and\nprepared versions and `agent-tool review carry <reviewed-head> <new-head>`\naccepts it; then report the review as carried, with both heads. Report\nreviewer, exact base and head IDs, verdict, remaining findings, validation, and\nany repairs performed. This skill does not authorize pushing, opening a PR, or\nmerging unless the user requested that work.\n",
4
4
  "explicit-state-machines": "---\nname: explicit-state-machines\ndescription: Find implicit state machines in a repository, or across many repositories, and refactor them into explicit ones (a closed set of states, typed events, one pure transition function) without changing behavior. Use when the user asks to \"find all of the implicit state machines\", to replace tangled boolean flags or scattered status writes, or to dogfood this pass across repositories; not for adding a state-machine library or redesigning features.\n---\n\n# Explicit State Machines\n\nAn implicit state machine is code that moves through modes (idle, loading,\nfailed, done) without naming them: several booleans that are only valid in\nsome combinations, a status string written from many places, nullable fields\nwhose presence means \"we are in phase X\", or effects that chain off each other\nto advance a process. Bugs live in the combinations nobody named:\n`isLoading && error`, a retry that fires after `done`, a dialog both open and\nsubmitting twice.\n\nAn explicit machine names every state once, carries each state's data only in\nthat state, and changes state only through one function of `(state, event)`.\nThe pass finds the implicit ones, converts those where the conversion removes\nimpossible states or scattered transitions, and proves behavior did not change.\n\n## Find candidates\n\n`agent-tool state-machines` ranks tracked source files by two signals:\nlifecycle booleans toggled together (`isLoading`, `hasError`,\n`_running`, `busy.current`, `this.#rendered`), and status-like fields assigned\nthree or more string values from three or more places (`step.status = ...`).\nIt reads extensionless scripts by their shebang and is read-only. It skips\nSQL comparisons, status fields whose every write is an `UPDATE` naming its\nfrom-state, and enum case payload labels (`.ended(shouldResume: true)`).\n\n- `agent-tool state-machines [path...] [--limit N] [--min-score N] [--json]`\n scans the current repository; each path names the repository holding it.\n If the repository's pinned agent-tool lacks the command, run\n `bunx --bun @a2f0/agent-tool@latest state-machines`.\n- `--limit N` (default 25 per repository, 0 for all), `--min-score N`\n (default 3), `--json` for agents.\n\nThe script finds leads, not verdicts, and it misses whole families. Also read\nfor these by hand, starting from the places state lives (stores, providers,\nhooks, workers, sync loops, connection handlers, upload and checkout flows,\nwizards, CLI subcommands that resume):\n\n- `loading`/`error`/`data` held as separate fields, or a nullable `error`\n beside a non-null `data`; any nullable value paired with a boolean or a\n second nullable (`nowPlaying` with `interruptedNoise`, `reservation` with\n `editing`). The scanner sees booleans only.\n- State split between a context and per-component state that an effect\n re-syncs, and \"already handled\" dedupe fields that quietly mean \"confirmed\n started\".\n- Fields that are set together and cleared together (`startedAt`, `jobId`,\n `abortController`) and so encode \"running\".\n- `useEffect` chains where one effect sets state that triggers the next.\n- Retry, polling, and reconnect loops guarded by counters and flags.\n- Status columns or enums whose transitions are enforced nowhere (any writer\n may set any value), in the database or in API handlers.\n- Shell, Python, or Expect scripts that track progress with several\n variables.\n- One nullable `error` shared by a load phase and user actions: starting an\n action clears the load's failure, so the view falls back to \"Loading...\"\n after a failed load. Split a `loading | ready | failed` load machine from\n the actions' own errors.\n\n## Decide what to convert\n\nConvert a candidate only when at least one holds:\n\n1. Two or more of its variables can hold a combination that is meaningless\n (`isLoading && isError`, `data` set while `status === \"failed\"`).\n2. Its transitions are written in several places, so no single place says\n which moves are legal.\n3. A bug or missing guard follows from either (an event handled in a state\n where it must be ignored). Fix the bug in the same change, with a test that\n fails before it, and say so in the PR.\n\nLeave it alone when the flags are independent (a theme toggle and a sidebar\ntoggle are a product of two machines, not one), when there is a single\nboolean, when a status is only read (an API response's field mirrored into\nUI), when it already is a discriminated union with one writer, or when the\nmodule is about to be deleted. Also leave alone:\n\n- Status columns whose writes all live in one module, each a conditional\n update naming the states it may leave (`UPDATE ... WHERE status = $from`),\n so that module reads as the transition table. Where writers are spread out\n or name no from-state, add one `ALLOWED` table and check it in the update\n instead; a value `CHECK` alone does not enforce transitions. A database\n transition trigger only restates a guarded module and breaks fixtures that\n simulate races by setting states.\n- Monotone flags with one writer each that move one way and are read only\n by cleanup (lock held, applying, committed), and append-only accumulators.\n- Static records checked by one validator, and before/after comparisons that\n validate rather than track progress.\n- Effect and promise guards (`cancelled`, `mounted`) on their own.\n- One request in flight plus one \"run again\" flag, both written from one\n function (`pending` with `started`): three reachable phases, one writer.\n- A ref mirroring a state to block a double click before re-render\n (`isSubmitting` with `isSubmittingRef`), written together. The missing\n mirror is the bug: a `busy` guard read from a click handler's render lets\n two clicks start the work twice.\n- Flags in different components (a parent's `editing`, and `busy` in a child\n that only exists while editing): the mount already excludes the bad pair.\n- Latest-wins request counters with one writer (`++request` paired with\n `request === current`): already the recommended guard, not a machine.\n- A one-time focus-return ref written together with the close event.\n- A single set-once setup flag (`isConfigured`).\n- A memoized single teardown promise (`closing ??= teardown()`) with a\n one-way `closed` flag only that teardown sets.\n- A boolean that is only an event's payload field\n (`interruptionEnded(shouldResume:)`): it is part of an event, not state.\n\nRecord each one you leave and why, so the next pass does not reread it.\n\n## Convert\n\nFollow `references/patterns.md` for the language at hand. In every language:\n\n1. List the states and the data each one carries; list the events. Write the\n transition table before the code, and keep it in the PR body.\n2. Model states as a closed type: a TypeScript discriminated union on a\n `status` (or the repository's existing tag name), a Swift enum with\n associated values, a Kotlin sealed interface, a Python `Enum` or tagged\n dataclasses, a Go typed constant with a transition function.\n3. Write one pure `transition(state, event)` (a reducer). Make the switch\n exhaustive (`never` check, `assertNever`, `@unique` enums, sealed `when`).\n Say explicitly what an event does in a state where it does not apply:\n ignore it (return the same state) or throw in development; never fall\n through silently.\n4. Keep every guard the old code had. A `cancelled` flag or an unmount check\n that drops a stale response must become a request tag carried by the\n state and its events (only the current request may finish), never a bare\n \"is it loading?\" check, which accepts `start(A) -> reset -> start(B) ->\n succeed(A)`. Test that sequence. A cleaned-up effect's callbacks (its own\n abort's rejection included) must not dispatch either; see `patterns.md`.\n5. Move side effects out of the transition: effects run on entering a state\n (a worker loop that switches on it, or an effect keyed on the state's whole\n identity: `status` plus its request tag), not inside the reducer. An\n effect keyed on `status` alone misses `loading(A) -> loading(B)` and never\n starts B; test a replacement request.\n6. Keep call sites small: derive old booleans from the state\n (`const isLoading = state.status === \"loading\"`) where many readers use\n them, rather than rewriting every consumer in the same change.\n7. Derive old booleans so they stay stable across intermediate states: an\n effect keyed on `editing` must not refire when a replacement passes\n through `reserving`. Keep effects tied to an event, not a state (resuming\n audio on a press), in the handler.\n8. Use no new dependency. Use a state-machine library (XState, Robot) only if\n the repository already depends on it.\n9. Test the transition table directly: every legal transition, a sample of\n ignored events per state, and the impossible combinations that the old\n code allowed. Keep the existing behavior tests passing unchanged; a test\n that must change shows a behavior change, which belongs in its own PR.\n Run the new behavior tests against the old file (`git show <base>:<file>`\n into a copy kept aside) to prove the refactor changed nothing and that a\n bug's regression test fails before its fix. For output that is printed or\n saved as JSON, assert key order too.\n10. Check every new guard against existing listeners: a guard that only acts\n in `ready` breaks a listener reacting to an event fired mid-render.\n11. Treat \"initial\" props (`initialEditing`) as one-time requests, on mount or\n when they turn true, not as levels that re-apply whenever another input\n changes. Fold a mirrored prop the machine depends on (`canWrite`) into the\n state, synced by one effect declared before the request effect.\n\n## Ship\n\n- Work on a `refactor/<topic>` branch (`fix/<topic>` when the change fixes a\n bug) and ship with the repository's `ship-pr` skill: its validation, its\n independent review, its merge policy.\n- Check file-count or naming budgets (ls-lint) before adding a machine module\n and its test; a full directory may need the tests in an existing file.\n- One PR per repository per pass, unless the diff passes about 600 lines or\n spans unrelated areas; then one PR per area, each independently valid. In\n large repositories plan one PR per machine: formatted transition tables\n and their tests grow fast.\n- The PR body lists each converted machine (file, states, events, the\n impossible combinations removed, any bug fixed) and each candidate left\n alone with its reason.\n- Repository-specific findings (where machines cluster, conventions such as\n the tag name or reducer location) go in that repository's agent guidance.\n Cross-repository lessons go in `references/lessons.md` here, by PR to\n agent-tool.\n\n## Across many repositories\n\nA pass over many repositories follows the coordinating workspace's sweep\nrules (status, ledger, one delegate per repository, `ship-pr` each). Run\n`agent-tool state-machines --json` in each repository first, attach its slice\nto that repository's delegate brief, and remind delegates to read beyond the\nscript's list.\nRepositories whose push hook or ship policy runs a full browser, simulator,\nor package gate need a heavy slot to ship: a delegate without one prepares a\nreviewed commit or open PR and hands off to a finisher that holds one.\n\n## Ownership\n\nagent-tool (`a2f0/agent-tool`) owns this skill in\n`skills/explicit-state-machines/`, and the `state-machines` scanner with its\ntests in `src/stateMachines/`. Repositories get it from\n`agent-tool skills install --apply`; do not edit the installed copy. Change it\nin agent-tool by PR, and send cross-repository lessons to\n`references/lessons.md` there. Repository-specific conventions still go in\nthat repository's `AGENTS.md`.\n",
5
5
  "open-issue": "---\nname: open-issue\ndescription: Open a GitHub issue the user explicitly requested, assigned to the authenticated GitHub user, with a reviewable title and body.\n---\n\n# Open Issue\n\nOpen an issue only when the user explicitly asks for one; finding a bug,\nrecording evidence, or following another skill does not authorize it. Follow\nrepository guidance for where issues belong, labels, and templates.\n\nResolve the target repository with `agent-tool repo context` (its `repo`\nfield) from the checkout, or the `owner/repo` the user named; never infer it\nfrom a folder name. Before creating, search open issues for a duplicate:\n\n```sh\ngh issue list --repo <owner/repo> --state open --search '<key words>' --json number,title,url\n```\n\nIf one matches, report it instead of opening another, and assign it with\n`gh issue edit <number> --repo <owner/repo> --add-assignee @me` when the user\nwants it tracked.\n\nWrite a specific title and a body that states the observed behavior, the\nexpected behavior, and reproduction steps or evidence (commands, versions,\nlinks). Never include secret values. Use only labels that already exist\n(`gh label list --repo <owner/repo>`). Put the body in a temporary file, then\ncreate the issue assigned to the authenticated GitHub user:\n\n```sh\ngh issue create --repo <owner/repo> --title '<title>' --body-file /path/to/issue-body.md --assignee @me\n```\n\nAlways pass `--assignee @me`; assign other people only when the user names\nthem, in addition to `@me` unless the user says otherwise. Confirm the result\nwith `gh issue view <url> --json url,assignees` and, if the assignee is missing,\nadd it with `gh issue edit <url> --add-assignee @me`. Report the issue URL and\nits assignees, or the exact error if assignment failed.\n",
6
6
  "open-pr": "---\nname: open-pr\ndescription: Open a GitHub pull request for the current feature branch with a validated title and a reviewable description.\n---\n\n# Open PR\n\nUse the installed `agent-tool`. Follow repository policy for validation, commits,\nand branch naming. Resolve the repository and default branch with `agent-tool repo context`;\ndo not assume the branch is named main. Preserve unrelated work and finish\nrequested changes and appropriate checks before publishing them.\n\nEnsure the intended commit is on a feature branch and use\n`agent-tool branch push <reviewed-head> --remote <remote>` through normal hooks.\nIt names the destination explicitly and verifies local/remote HEAD afterward;\na changed result needs another review. Respect existing push authorization.\nIf the user only requested a draft description, prepare it without publishing.\n\nWrite a title that satisfies the data-only `agent-tool.json` subject policy.\nDescribe the concrete resulting behavior and relevant validation. When the\nbranch changes package manifests, run\n`agent-tool dependencies diff --base <base-oid>` and name every `newPackages`\nentry in the body with its manifest and version, so a reviewer sees new\nthird-party code however it was added. Put multiline body text in a temporary\nfile, then run:\n\n```sh\nagent-tool pr open 'feat: describe the change' --body-file /path/to/pr-body.txt\n```\n\nOmitting the title uses the latest commit subject. The tool refuses duplicate\nopen PRs and requires the branch to be pushed at its local HEAD. It does not\npush for you. Resolve a fork's head/base identities explicitly if the repository\nuses fork PRs; the initial open helper supports same-repository branches.\n\nReport the created PR link and any remaining validation or review work. Run\n`agent-tool teardown` first, stop what the work started, and report what remains.\n",
7
7
  "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",
8
- "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.\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, push, and wait again. 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 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, 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",
9
- "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. Read unresolved feedback with\n`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,\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",
8
+ "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",
9
+ "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",
10
10
  "update-dependencies": "---\nname: update-dependencies\ndescription: Update dependencies or update everything in a repository, including runtimes, tools, and CI pins, with compatibility checks and safe previews; ship through review, CI, merge, and release verification unless a narrower scope is requested.\n---\n\n# Update Dependencies\n\nUse the repository's package managers and installed `agent-tool`. Read `AGENTS.md`,\nREADME, existing dependency-maintenance notes, linked setup/release documents,\nand repository-owned upgrade skills before editing. Follow their hooks, version\npolicy, checks, and requested stopping point.\nUpdate applicable dependencies throughout the repository, including workspaces\nand examples. When asked to perform dependency updates, invoke the installed\n[`ship-pr`](../ship-pr/SKILL.md) to complete review, PR, CI, and merge, then verify\nthe repository's normal merge-triggered publication or deployment. An explicit\nnarrower scope, such as inventory-only, local changes, or open-PR-only, takes\nprecedence. This default does not authorize standalone infrastructure applies,\ndeployments, or global tool changes. Default dependency-update merge subject:\n`chore: update dependencies`, subject to repository title policy and any explicit\nuser subject.\n\nRun noisy installs, checks, tests, and builds with\n`agent-tool run --label <check> -- <command> [args...]` to retain full private\nlogs and return the original status with compact output. Inspect bounded excerpts\nusing `agent-tool logs <log>` and targeted searches for warnings and evidence;\na successful receipt does not establish a warning-free upgrade. Keep structured\naudit/plan results, deployment previews, and review findings directly visible\nwhen they drive a safety decision. Do not dump full suite logs into context,\nsilence warnings at their source, or change check scope to reduce output.\n\n## Checkout setup\n\nThis shared workflow also handles natural-language requests to \"update everything\".\nIf the repository owns an `update-everything` wrapper, read and follow its extra\nrequirements; do not create an alias or overwrite that skill. The workflow works\nfrom a standalone checkout with no workspace coordinator.\n\nAfter a fetch, branch integration, or dependency pin change, check that the local\n`agent-tool --version` matches the repository's declared pin before trusting its\ncommands or generated skills. A stale CLI can reject newer configuration keys.\nAfter screening install scripts and hooks as below, run the documented frozen\ninstall with the repository's pinned runtime. For Bun projects, an already working\nCLI can run `agent-tool bun install`; if it is missing or cannot parse the new\nconfig, run the documented package-manager install directly. A known working\nexecutable may capture it with `agent-tool --repo <checkout> run --label setup --\n<install-command> [args...]`. Do not fetch an unpinned CLI, alter global tools, or\nassume a sibling workspace exists. Verify the installed version afterward; if it\nstill differs, report the mismatch rather than deleting arbitrary dependencies.\n\nAfter upgrading agent-tool, run the repository's skill/permission sync commands\n(or `agent-tool skills install --harness <existing-scope> --apply`), preserve its\nharness scope, and commit ownership manifests with generated files. Hermes reads\nthe shared `.agents/skills` in a trusted project; the installer does not grant\ntrust. If discovery is unavailable, read those files directly rather than silently\nusing a stale global copy.\n\n## Nonblocking execution\n\nUse the harness's managed background execution for long finite checks, reviews,\npush hooks, CI waits, and release verification; request completion notification\nwhen available and retain its process handle plus agent-tool's log/receipt path.\nRun `run-group` and reviews directly so their reports remain visible. A started\nprocess is not a passed check: read its final status and required evidence before\nshipping, and do not repeatedly poll when completion events are available.\nWithout harness background support, `proc start --label <name> -- agent-tool run\n--label <check> -- <command> [args...]` records the outer process and captures\nits output; inspect `proc list` and `logs` plus the inner run receipt to establish\ncompletion and exit status. An exited process record alone does not prove success.\nUse `proc stop`/`teardown` for owned leftovers; never stop another session's work.\nThese commands need no matrix workspace or global configuration change.\n\nKeep independent compatibility groups moving while a producer release or an\nexternal gate is pending. Only final adoption of that exact published release\nmust wait. Bound CPU/process-heavy concurrency to the machine's available budget;\na failed full suite needs diagnosis and a full-scope rerun, not larger timeouts,\nfewer assertions, or a focused retry presented as suite recovery. Background\nexecution never bypasses an approval, a deployment preview, or exact-head review.\n\n## Safety before execution\n\n**Always dry-run before any infrastructure apply or deployment. Never destroy,\nreplace, or recreate a resource during an upgrade.** This includes Terraform,\nOpenTofu, Wrangler, Ansible, other infrastructure tools, and effects triggered by\ninstallation, tests, hooks, Git push, opening a PR, CI, or merging. Greenfield\nprojects and approval to ship do not waive this rule.\n\nBefore running project commands or pushing, trace their scripts, hooks, workflow\ntriggers, reusable workflows, and deployment commands. A dry-run flag alone is\ninsufficient: inspect tasks, provisioners, plugins, external programs, and actions\nthat can mutate despite preview mode. Avoid such a preview unless its effects\nare proven read-only. Do not run destroy/delete, taint/replace, state removal,\nbackend migration, forced database reset, or an automatic \"repair\" that bypasses\nthe rule. Do not hide destruction with targeting, disabled refresh, ignored\nchanges, new resource identities, or weakened policy.\n\nPreview with the proposed versions and complete configuration for each affected\nenvironment, using its real backend/workspace/account, variables, inventory, and\nresource identities. An empty local state, mocked credentials, validate-only run,\nor bundle build cannot establish safety for production. Check the current baseline\nas well when needed to distinguish existing drift from the upgrade. Keep state,\nbinary plans, JSON plans, and secret-bearing diffs out of Git and public reports.\n\nIf a preview proposes deletion or replacement, fails, is incomplete, omits\naffected resources, or cannot establish safety, skip that dependency and its\ncoupled migrations. Restore only this task's edits to the affected compatibility\ngroup, retain independent safe upgrades, and record the reason and affected\nresources. Never apply to find out. A preview is not deployment authorization.\n\nBefore an authorized apply/deploy, verify the exact validated commit, toolchain,\nconfiguration, environment, and current state still match the preview. Re-preview\nafter relevant changes or drift. CI must enforce the same order and stop on an\nunsafe preview before mutation; a successful local preview does not excuse an\nunguarded push- or merge-triggered deployment. Establish a narrowly scoped guard\nwhen authorized and reviewable, or hold the affected upgrade before triggering\nthat workflow. Do not disable protections to ship. A plan must be inspected before\nthe operation; inspecting deployment logs afterward is too late.\nAn unsafe workflow triggered on every branch push also blocks pushing otherwise\nindependent upgrades until that trigger has a proven safe guard.\n\n### Terraform and OpenTofu\n\nRead core, provider, and module upgrade guides, including intermediate major\nmigrations. Regenerate provider locks with the pinned CLI, preserving supported\nplatform hashes. Backend initialization/migration is also subject to the safety\ngate. Inspect external data programs and provisioners before planning.\n\nUse a full refreshed saved plan with locking and the real variables, for example\n`terraform plan -input=false -out=<private-plan>`; if using `-detailed-exitcode`,\n0 and 2 are success, 1 is failure. Inspect `terraform show -json <private-plan>`.\nRun `agent-tool dependencies check-terraform-plan <private-plan.json>` to check\nsupported JSON resource actions. It fails for every action containing `delete`,\nincluding both replacement orders, unknown actions, incomplete/deferred plans,\nfailed checks, or opaque provider action invocations. It prints actions and\ndiagnostics without resource attribute values; it does not prove that a plan is\nfresh, comprehensive, authentic, or that provider code has no hidden effects.\nOlder/unsupported plan formats that cannot establish completeness are skipped.\nOpenTofu currently omits `complete` in its JSON format and is rejected by this\nhelper; report that limitation rather than adding a synthetic completeness flag.\nAlso inspect resource identity, drift, warnings, provider semantics, and any\neffects outside resource actions. For an authorized apply, consume the exact\napproved saved plan, not an uninspected newly generated plan.\n\nSource: [Terraform JSON plan format](https://developer.hashicorp.com/terraform/internals/json-format).\n\n### Wrangler and other deployment tools\n\nUse the proposed pinned Wrangler for `wrangler deploy --dry-run` with the same\nbuild/configuration/environment used by deployment. This checks bundling, not a\ncomplete remote resource plan. Separately verify account, worker name, routes,\nbindings and resource IDs against the existing deployment and read migration\nsemantics. Review Durable Object deleted/renamed classes, D1 schema/data\nmigrations, storage resources, queues, containers, and deployment integrations.\nNever infer \"no destruction\" from a successful bundle. Resource removals,\nreplacement, or unprovable remote effects skip the affected group. Apply the\nequivalent preview and identity checks to other tools rather than assuming they\nshare Terraform's guarantees.\n\nDo not assume `wrangler d1 migrations list --remote` is read-only. The\nimplementation inspected for this skill initializes migration tracking with\n`CREATE TABLE IF NOT EXISTS`; verify the pinned Wrangler version before using\nthe command. Verify database identity and compare migration files with the\ndatabase's configured migration tracking table through audited read-only\nqueries. A missing table, pending migration, or unverifiable schema/data\neffects hold the affected upgrade/deployment group. Never initialize schema\nmerely to establish preview safety.\n\nWrangler runs a custom `build.command` again during deployment. Use supported\nconfiguration referencing the same validated artifacts for both preview and\ndeployment, preventing another unvalidated build before upload. Bind the\nartifacts, configuration, and pinned tool to the authorized commit, and recheck\ntheir identities before upload and after relevant changes. Hold the affected\ngroup if the pinned Wrangler cannot upload the validated output without\nrebuilding it, or if the upload cannot be proven to match the preview.\n\nSources: [Wrangler command documentation](https://developers.cloudflare.com/workers/wrangler/commands/),\n[D1 migration listing implementation](https://github.com/cloudflare/workers-sdk/blob/e3d186776fcc2e4b5cc4cfd7155591778a375957/packages/wrangler/src/d1/migrations/list.ts),\n[migration table initialization](https://github.com/cloudflare/workers-sdk/blob/e3d186776fcc2e4b5cc4cfd7155591778a375957/packages/wrangler/src/d1/migrations/helpers.ts),\nand [Wrangler custom builds](https://developers.cloudflare.com/workers/wrangler/custom-builds/).\n\n### Ansible\n\nCheck controller Python, ansible-core, collections/roles, and target Python support\ntogether; read porting guides. Inspect all tasks and invoked scripts before\n`ansible-playbook --check --diff` with the real inventory and variables.\n`check_mode: false` forces mutation even with `--check`; unsupported modules and\nconditions based on registered results can omit effects. Inspect deletion,\nrecreation, service/data reset, and package removal semantics beyond the diff.\nSkipped or opaque tasks are a safety gap, not a clean preview. Redact diffs.\n\nSource: [Ansible check mode limits](https://docs.ansible.com/projects/ansible/latest/playbook_guide/playbooks_checkmode.html).\n\n## Inventory and choose compatible targets\n\nRecord each dependency source, current resolved version, latest stable candidate,\nselected target, compatibility constraints, upstream migration links, and checks\nin the run ledger described under Report.\nQuery authoritative registries, official releases, support matrices, and migration\nguides at execution time; do not treat remembered versions or prereleases as\nlatest stable. Inspect runtime requirements, peer dependencies, ABI/API changes,\nplatform availability, maintained release lines, and changed defaults, including\nsecurity, privacy/telemetry, data retention, and postinstall/native behavior.\nCheck transitive dependencies' peer/runtime constraints as well as direct ones. Unsupported\nor unpublished targets stay pinned with an explanation.\n\nInventory manifests, locks, tool configuration, CI/reusable actions, containers,\nscripts, deployment files, and executable documentation. Search duplicate version\npins and aliases, not just filenames; exclude vendored/generated snapshots unless\nthe repository owns their update process. Examples of sources to inspect:\n\n| Ecosystem | Sources and compatibility group |\n| --- | --- |\n| JavaScript/TypeScript | All package.json dependency fields, overrides/resolutions, workspace catalogs, packageManager/engines, npm/Bun/pnpm/Yarn locks, Node/Bun pins, compiler and lint/build/test plugins |\n| Toolchains | mise.toml/.mise.toml, mise.lock, .tool-versions, runtime version files, tool URLs/checksums, CI pins and container images; include every tool declared by mise, not just mise itself |\n| Python/Ansible | pyproject/requirements, uv/Poetry/pip locks, Python pins, ansible-core, collection/role requirements, lint plugins and managed host constraints |\n| Ruby/iOS | .ruby-version, Gemfile/lock, Bundler, CocoaPods, Podfile/lock, podspecs, Swift packages and Xcode/iOS deployment requirements |\n| Infrastructure | Terraform/OpenTofu CLI constraints, provider locks/constraints, module versions/Git refs, Wrangler and Cloudflare integration dependencies |\n| CI/system/native | Actions/reusable workflow refs, Docker tags/digests, OS images/packages, Rust/Cargo toolchain and locks, Go modules, Gradle/AGP/Kotlin/JDK and other repository-specific manifests |\n\nBuild connected compatibility groups before editing. Select the newest supported\ncombination, which can be older than an individual package's latest. Upgrade the\nframework first or keep its compatible toolchain pinned; do not force peer\nresolution, drop compatibility checks, or add blanket overrides to make installs\npass. Preserve source pin policy (exact version, digest, full Git SHA) and resolve\nimmutable pins from verified upstream releases. Preserve intentional runtime\nminimums unless migration requires changing the support contract.\n\nFor React Native, use its version-specific upgrade guide/template diffs and\nrepository upgrade skills. Couple React and its renderer, native modules,\nMetro/Babel, CLI, codegen, Hermes/New Architecture, CocoaPods/Bundler/Ruby,\nXcode/iOS deployment targets, and Android Gradle/AGP/Kotlin/JDK/SDK/NDK. For Expo,\nuse the chosen SDK's supported React Native/dependency matrix and its dependency\nchecks. Do not independently update framework-managed pods or generated native\nfiles; use the framework's regeneration workflow and prove iOS/Android builds.\nPermissive peer ranges alone do not prove native renderer or toolchain compatibility;\ncheck the framework's actual supported versions and native implementation.\nAn unavailable native toolchain is a reported validation limit; do not claim the\ngroup verified. See [React Native upgrading](https://reactnative.dev/docs/upgrading).\n\nCheck developer tools' own dependencies too: a compiler release without its old\nprogrammatic API may break test/lint runners that import it even when `tsc` passes.\nAction runtime upgrades can require newer self-hosted runners; preserve workflow\npermissions, action inputs/outputs, caching, artifact semantics, and job names.\n\nCheck current advisories with read-only ecosystem audits against the baseline and\nproposed lockfiles, using the repository's configured registry/advisory sources.\nDo not send private dependency metadata to an unconfigured or unauthorized service;\nreport the resulting coverage limit. Cover direct and resolved transitive dependencies,\nincluding native/platform-specific binaries. Latest direct packages can still\npin vulnerable transitive versions. Trace each finding to its owning dependency,\nverify affected versions, runtime conditions, and remediation in the maintainer's\nadvisory and fixed release. When the owner's range permits a fixed version, use a\ntargeted refresh with the lockfile's owning manager and preserve unrelated\nresolutions; otherwise prefer a supported owner upgrade.\nIf the owner still pins a vulnerable version, a narrowly scoped security patch\noverride may be used only with API/ABI/runtime compatibility evidence and focused\nregression checks of the actual affected integration. Document its rationale and\nremoval condition; a passing install or bundle alone is insufficient. Do not run\nblind audit fixes or use blanket overrides to bypass compatibility constraints.\nReport unresolved advisories and unavailable audit coverage accurately; current\ndirect pins or a partial clean audit do not\nestablish that the whole dependency graph is safe.\n\n## Migrate and validate\n\nCapture relevant baseline checks and warnings first, after screening their side\neffects. Update one compatibility group at a time. Read the upstream instructions\nfor every breaking step; implement required source/config/schema migrations and\nremoved API replacements. Use the manager that owns each lockfile, on the selected\nruntime, and inspect the resulting diff. For Bun lockfiles, change declared\nversions with `agent-tool bun update <name[@version]>` and drop packages with\n`agent-tool bun remove <name>`; both use the pinned Bun and refuse to add a\npackage. A new dependency goes through `agent-tool bun add <name@version>`, which\nasks for approval; never introduce one by editing `package.json` and\nreinstalling. For existing Bun catalog entries use\n`agent-tool bun update --catalog default <name@version>...` (or the existing named\ncatalog). Name an explicit exact/ranged registry spec; keep `catalog:` references,\nworkspace membership, other entries, and peer compatibility contracts intact.\nThe helper refuses intake and ambiguous layouts and uses the owning manager to\nrefresh the lock; do not replace catalog references with direct versions.\n\nFor an already-resolved transitive registry package with an eligible owner range,\nuse `agent-tool bun update --resolved <name>...` with the owning Bun 1.4.4 or newer.\nIt selects every locked copy of those names, never a requested version or glob,\nand accepts only a result with identical manifests and unchanged non-target lock\nentries/metadata. It preserves release-age, overrides and patches. If an older\nmanager is pinned, or a required new child prevents a target-only result, this\npath is unsupported: prefer an owning-dependency upgrade through the normal\nhelper, or obtain approval for an explicitly reviewed manager workflow. Do not\nsilently substitute a broad refresh or add a transitive package directly. Inspect\nthe receipt/logs and re-audit; a no-op or warning can leave an advisory unresolved.\nNever hand-edit integrity hashes or lock entries.\nReview intentional patches, overrides, and pins before removal; retain them until\nupstream fixes and regression checks demonstrate they are unnecessary.\nAvoid unrelated global installations or environment changes. Use task-local or\nrepository-scoped tools for testing changed runtime pins.\nFor published packages, also validate tarballs and consumer installs with their\ndocumented supported package managers, including manifest/override syntax and\nruntime requirements. A successful owning-manager install does not prove that\npublished metadata works for those consumers.\n\nRun the repository's setup/hooks, frozen installs, lint, typechecks, tests, builds,\npackage/platform smoke checks, and relevant safe integration previews. Resolve\nupgrade-related deprecation warnings at their source. Do not suppress warnings,\nweaken tests, or disable checks; report remaining upstream/pre-existing warnings\nwith evidence and keep a target pinned when migration cannot be completed.\nAdd focused regression coverage when a migration changes behavior; avoid tests\nthat merely assert version strings. Re-run checks after repairs. Report checks\nblocked by missing credentials, platforms, or external services accurately.\nRe-audit the final resolved graph after migrations and repairs.\n\nConfirm every inventory row is upgraded, already current, intentionally constrained,\nor skipped with a concrete reason. Do not present an unresolved group as complete.\nWhen upgrading agent-tool itself, install its managed skills with the same harness\nscope and commit the ownership manifest; never edit generated managed skill copies.\n\nWhen changes depend on another repository's release, ship the producer first and\nconfirm publishing and registry availability before pinning the consumer; include\nits exact version/commit and API migration notes. Independent groups may proceed.\nComplete the installed `ship-pr` workflow within the requested scope, including\nindependent review of every changed HEAD, required CI and review feedback, merge,\nand verification of the merge's normal publication or deployment. Do not stop at\nan open PR unless the user requested that stopping point or a concrete blocker\nprevents continuing. Check deployment safety again before push/open/merge;\nshipping defaults do not waive the preview gates above.\n\n## Report\n\nKeep run-specific evidence in the upgrade PR body or a linked PR comment: the\ninventory and old/selected versions, completed migrations, validation and warnings,\nbaseline/final audits and coverage limits, preview environment/commit/tool versions\nand safe action summary, and skipped/constrained dependencies with reasons. Include\nsecurity overrides, their rationale and removal condition, and unresolved advisories.\nIf the user requested a scope that stops before a PR, provide this ledger in the\ntask report and honor that limit. For a sweep, keep one entry per repository,\nincluding unready and unchanged checkouts, and use an existing tracking issue only\nwhen explicitly requested. Never create an issue merely to store upgrade evidence.\n\nKeep durable repository guidance focused on what the next upgrade needs: current\ncompatibility constraints, intentional pins/overrides, unresolved advisories, and\nreusable repository-specific procedures. Prefer the existing maintenance document;\notherwise create `docs/dependency-upgrades.md` (or the repository's equivalent)\nonly when there is substantive guidance to preserve. For each constraint, record\nits rationale, upstream advisory/migration/issue link or originating PR, and the\ncondition and check for removing or revisiting it. Do not copy version inventories,\naudit output, validation/preview receipts, or dated run journals into that document.\n\nOn every upgrade, reconcile the existing maintenance document against the final\ndependency graph and checks: update constraints in place, remove resolved entries,\nand link the PR for historical evidence. Keep the root README focused on purpose,\nsetup, supported requirements, and normal usage, with a concise maintenance link\nwhen needed. Keep dependency-maintenance guidance in `AGENTS.md` to a short\nrouting rule and link; do not accumulate upgrade reports in either entrypoint\nor duplicate the maintenance document.\n\nFor shipping, report the branch, reviewed commit/verdict, PR, merge, publish/deploy\nresult, and final checkout state. Keep full logs private; never publish credentials,\nstate, or plan contents in any of these locations.\n"
11
11
  };
12
12
  /** Markdown files a skill ships beside its SKILL.md, by skill and then by path within the skill directory. */
@@ -63,6 +63,7 @@ function changedFiles(
63
63
  rootDir: string,
64
64
  mergeBase: string,
65
65
  packageDir: string,
66
+ head: string,
66
67
  ): string[] {
67
68
  return git(rootDir, [
68
69
  "diff",
@@ -70,7 +71,7 @@ function changedFiles(
70
71
  "--no-renames",
71
72
  "-z",
72
73
  mergeBase,
73
- "HEAD",
74
+ head,
74
75
  "--",
75
76
  packageDir,
76
77
  ])
@@ -87,9 +88,10 @@ function packageChanged(
87
88
  mergeBase: string,
88
89
  packageDir: string,
89
90
  headManifest: string,
91
+ head: string,
90
92
  ): boolean {
91
93
  const manifest = manifestPath(packageDir);
92
- const changed = changedFiles(rootDir, mergeBase, packageDir);
94
+ const changed = changedFiles(rootDir, mergeBase, packageDir, head);
93
95
  if (changed.some((file) => file !== manifest)) {
94
96
  return true;
95
97
  }
@@ -125,44 +127,46 @@ function bundledPackageChanged(
125
127
  rootDir: string,
126
128
  mergeBase: string,
127
129
  packageDir: string,
130
+ head: string,
128
131
  ): boolean {
129
132
  const manifest = manifestPath(packageDir);
130
- const changed = changedFiles(rootDir, mergeBase, packageDir);
133
+ const changed = changedFiles(rootDir, mergeBase, packageDir, head);
131
134
  if (changed.some((file) => file !== manifest)) return true;
132
135
  if (!changed.includes(manifest)) return false;
133
136
  return (
134
137
  withoutVersion(showFile(rootDir, mergeBase, manifest)) !==
135
- withoutVersion(showFile(rootDir, "HEAD", manifest))
138
+ withoutVersion(showFile(rootDir, head, manifest))
136
139
  );
137
140
  }
138
141
 
139
142
  /**
140
- * The version each package should carry at HEAD to merge onto `baseCommit`:
141
- * one patch past the base when the branch changes the package or a package it
142
- * bundles, the base's own version when it does not, and a deliberate major or
143
- * minor bump left alone.
143
+ * The version each package should carry at `head` (HEAD by default) to merge
144
+ * onto `baseCommit`: one patch past the base when the branch changes the
145
+ * package or a package it bundles, the base's own version when it does not,
146
+ * and a deliberate major or minor bump left alone.
144
147
  */
145
148
  export function planVersions(
146
149
  rootDir: string,
147
150
  baseOid: string | undefined,
151
+ head = "HEAD",
148
152
  ): VersionPlan[] {
149
153
  const baseCommit = resolveBaseCommit(rootDir, baseOid);
150
- const mergeBase = git(rootDir, ["merge-base", baseCommit, "HEAD"]).trim();
151
- const bundles = bundledPackages(rootDir);
154
+ const mergeBase = git(rootDir, ["merge-base", baseCommit, head]).trim();
155
+ const bundles = bundledPackages(rootDir, head);
152
156
  const bundledChanges = new Map<string, boolean>();
153
157
  const bundledChanged = (packageDir: string): boolean => {
154
158
  let result = bundledChanges.get(packageDir);
155
159
  if (result === undefined) {
156
- result = bundledPackageChanged(rootDir, mergeBase, packageDir);
160
+ result = bundledPackageChanged(rootDir, mergeBase, packageDir, head);
157
161
  bundledChanges.set(packageDir, result);
158
162
  }
159
163
  return result;
160
164
  };
161
165
  const plans: VersionPlan[] = [];
162
- for (const packageDir of workspacePackages(rootDir)) {
166
+ for (const packageDir of workspacePackages(rootDir, head)) {
163
167
  const manifest = manifestPath(packageDir);
164
168
  const baseManifest = showFile(rootDir, baseCommit, manifest);
165
- const headManifest = showFile(rootDir, "HEAD", manifest);
169
+ const headManifest = showFile(rootDir, head, manifest);
166
170
  if (headManifest === null) {
167
171
  continue;
168
172
  }
@@ -177,7 +181,7 @@ export function planVersions(
177
181
  if (isReleaseBump(headVersion, baseVersion)) {
178
182
  targetVersion = headVersion;
179
183
  } else if (
180
- packageChanged(rootDir, mergeBase, packageDir, headManifest) ||
184
+ packageChanged(rootDir, mergeBase, packageDir, headManifest, head) ||
181
185
  (bundles.get(packageDir) ?? []).some(bundledChanged)
182
186
  ) {
183
187
  targetVersion = bumpPatch(baseVersion);
@@ -12,16 +12,16 @@ interface WorkspaceManifest {
12
12
  dependencies?: unknown;
13
13
  }
14
14
 
15
- function headManifest(rootDir: string, packageDir: string): WorkspaceManifest {
15
+ function headManifest(rootDir: string, packageDir: string, commit: string): WorkspaceManifest {
16
16
  const file = manifestPath(packageDir);
17
- const result = spawnSync("git", ["show", `HEAD:${file}`], {
17
+ const result = spawnSync("git", ["show", `${commit}:${file}`], {
18
18
  cwd: rootDir,
19
19
  env: gitEnvironment(),
20
20
  encoding: "utf8",
21
21
  stdio: ["ignore", "pipe", "ignore"],
22
22
  });
23
23
  if (result.error) throw result.error;
24
- if (result.status !== 0) throw new Error(`${file} is not committed at HEAD.`);
24
+ if (result.status !== 0) throw new Error(`${file} is not committed at ${commit}.`);
25
25
  return JSON.parse(result.stdout);
26
26
  }
27
27
 
@@ -42,21 +42,21 @@ function workspaceDependencies(manifest: WorkspaceManifest): string[] {
42
42
  /**
43
43
  * The workspace packages each configured bundle ships inside its own artifact:
44
44
  * every package it reaches through `workspace:` ranges in `dependencies`, read
45
- * from HEAD. A change to any of them is a change to the bundle.
45
+ * from `commit`. A change to any of them is a change to the bundle.
46
46
  */
47
- export function bundledPackages(rootDir: string): Map<string, string[]> {
47
+ export function bundledPackages(rootDir: string, commit = "HEAD"): Map<string, string[]> {
48
48
  const bundles = loadConfig(rootDir).versions.bundles;
49
49
  const result = new Map<string, string[]>();
50
50
  if (bundles.length === 0) return result;
51
- const versioned = workspacePackages(rootDir);
51
+ const versioned = workspacePackages(rootDir, commit);
52
52
  // Discovered only when a bundle has a workspace dependency, so a bundle
53
53
  // without any needs no workspace declaration.
54
54
  let directories: Map<string, string> | undefined;
55
55
  const directoryOf = (name: string): string | undefined => {
56
56
  if (directories === undefined) {
57
57
  directories = new Map();
58
- for (const packageDir of discoveredWorkspaces(rootDir)) {
59
- const manifest = headManifest(rootDir, packageDir);
58
+ for (const packageDir of discoveredWorkspaces(rootDir, commit)) {
59
+ const manifest = headManifest(rootDir, packageDir, commit);
60
60
  if (typeof manifest.name === "string") directories.set(manifest.name, packageDir);
61
61
  }
62
62
  }
@@ -67,7 +67,7 @@ export function bundledPackages(rootDir: string): Map<string, string[]> {
67
67
  throw new Error(`versions.bundles names ${bundle}, which is not a versioned package.`);
68
68
  }
69
69
  const reached = new Set<string>();
70
- const pending = workspaceDependencies(headManifest(rootDir, bundle));
70
+ const pending = workspaceDependencies(headManifest(rootDir, bundle, commit));
71
71
  for (let name = pending.pop(); name !== undefined; name = pending.pop()) {
72
72
  const packageDir = directoryOf(name);
73
73
  if (packageDir === undefined) {
@@ -75,7 +75,7 @@ export function bundledPackages(rootDir: string): Map<string, string[]> {
75
75
  }
76
76
  if (packageDir === bundle || reached.has(packageDir)) continue;
77
77
  reached.add(packageDir);
78
- pending.push(...workspaceDependencies(headManifest(rootDir, packageDir)));
78
+ pending.push(...workspaceDependencies(headManifest(rootDir, packageDir, commit)));
79
79
  }
80
80
  result.set(bundle, [...reached].sort());
81
81
  }
@@ -6,14 +6,14 @@ import {
6
6
  import { posix } from "node:path";
7
7
  import { loadConfig } from "../config";
8
8
 
9
- /** The versioned packages: the configured directories, or every workspace. */
10
- export function workspacePackages(rootDir: string): string[] {
9
+ /** The versioned packages: the configured directories, or every workspace committed at `commit`. */
10
+ export function workspacePackages(rootDir: string, commit = "HEAD"): string[] {
11
11
  const configured = loadConfig(rootDir).versions.packages;
12
- return configured === null ? discoveredWorkspaces(rootDir) : [...configured];
12
+ return configured === null ? discoveredWorkspaces(rootDir, commit) : [...configured];
13
13
  }
14
14
 
15
- /** Discover every committed workspace, including globbed and newly added ones. */
16
- export function discoveredWorkspaces(rootDir: string): string[] {
15
+ /** Discover every workspace committed at `commit`, including globbed and newly added ones. */
16
+ export function discoveredWorkspaces(rootDir: string, commit = "HEAD"): string[] {
17
17
  const options: ExecFileSyncOptionsWithStringEncoding = {
18
18
  cwd: rootDir,
19
19
  env: gitEnvironment(),
@@ -21,7 +21,7 @@ export function discoveredWorkspaces(rootDir: string): string[] {
21
21
  stdio: ["ignore", "pipe", "pipe"],
22
22
  };
23
23
  const root: { workspaces?: string[] | { packages?: string[] } } = JSON.parse(
24
- execFileSync("git", ["show", "HEAD:package.json"], options),
24
+ execFileSync("git", ["show", `${commit}:package.json`], options),
25
25
  );
26
26
  const patterns = Array.isArray(root.workspaces)
27
27
  ? root.workspaces
@@ -30,7 +30,7 @@ export function discoveredWorkspaces(rootDir: string): string[] {
30
30
  throw new Error("package.json must declare workspace package paths.");
31
31
  }
32
32
  const globs = patterns.map((pattern) => new Bun.Glob(pattern));
33
- return execFileSync("git", ["ls-tree", "-rz", "--name-only", "HEAD"], options)
33
+ return execFileSync("git", ["ls-tree", "-rz", "--name-only", commit], options)
34
34
  .split("\0")
35
35
  .filter((file) => file.endsWith("/package.json"))
36
36
  .map((file) => posix.dirname(file))
@@ -26,16 +26,18 @@ function stage(rootDir: string, index: 1 | 2 | 3, file: string): string {
26
26
  return git(rootDir, ["show", `:${index}:${file}`]);
27
27
  }
28
28
 
29
+ function mergeIgnoringVersion(rootDir: string, file: string): string | null {
30
+ return mergeManifestIgnoringVersion(rootDir, stage(rootDir, 1, file), stage(rootDir, 2, file), stage(rootDir, 3, file));
31
+ }
32
+
29
33
  /**
30
34
  * Three-way merge a manifest with every side's version set to one version, so
31
35
  * a version-only conflict merges cleanly: the branch's when it is a deliberate
32
36
  * major or minor release over the incoming base, which `bumpVersions` keeps,
33
37
  * and the base's otherwise. Null when anything besides the version still
34
- * conflicts.
38
+ * conflicts. `review carry` repeats it to check a recorded resolution.
35
39
  */
36
- function mergeIgnoringVersion(rootDir: string, file: string): string | null {
37
- const ours = stage(rootDir, 2, file);
38
- const theirs = stage(rootDir, 3, file);
40
+ export function mergeManifestIgnoringVersion(rootDir: string, mergeBase: string, ours: string, theirs: string): string | null {
39
41
  const oursVersion = readVersion(ours);
40
42
  const theirsVersion = readVersion(theirs);
41
43
  const version = isReleaseBump(oursVersion, theirsVersion)
@@ -45,7 +47,7 @@ function mergeIgnoringVersion(rootDir: string, file: string): string | null {
45
47
  try {
46
48
  const inputs = {
47
49
  ours: withVersion(ours, version),
48
- base: withVersion(stage(rootDir, 1, file), version),
50
+ base: withVersion(mergeBase, version),
49
51
  theirs: withVersion(theirs, version),
50
52
  };
51
53
  const paths = Object.entries(inputs).map(([name, source]) => {
@@ -259,7 +259,9 @@ export interface PushGateCheck {
259
259
  notes: string[];
260
260
  }
261
261
 
262
- /** Read-only: the tracked hook is the canonical body, hooks.files installs it, and no step runs tests or installs unless it says why. */
262
+ const FINDING_TEXT: Record<StepFinding["kind"], string> = { test: "a test run", build: "a build", install: "a dependency install" };
263
+
264
+ /** Read-only: the tracked hook is the canonical body, hooks.files installs it, and no step runs tests, builds, or installs unless it says why. */
263
265
  export function checkPushGate(root: string, config: AgentToolConfig): PushGateCheck {
264
266
  const errors: string[] = [], notes: string[] = [];
265
267
  const tracked = spawnSync("git", ["ls-files", "--error-unmatch", "--", PRE_PUSH_SOURCE], { cwd: root, stdio: "ignore", env: gitEnvironment() }).status === 0;
@@ -278,7 +280,7 @@ export function checkPushGate(root: string, config: AgentToolConfig): PushGateCh
278
280
  const steps = (gate?.steps ?? []).map(step => {
279
281
  const { findings, errors: stepErrors } = resolveStep(root, step.command);
280
282
  const ok = !stepErrors.length && (!findings.length || !!step.allowSlow);
281
- for (const finding of step.allowSlow ? [] : findings) errors.push(`Step '${step.label}' runs ${finding.kind === "test" ? "a test run" : "a dependency install"} (${finding.runner}): ${finding.chain.join(" -> ")}. Move it to CI, or give the step an allowSlow reason.`);
283
+ for (const finding of step.allowSlow ? [] : findings) errors.push(`Step '${step.label}' runs ${FINDING_TEXT[finding.kind]} (${finding.runner}): ${finding.chain.join(" -> ")}. Move it to CI, or give the step an allowSlow reason.`);
282
284
  for (const error of stepErrors) errors.push(`Step '${step.label}': ${error}`);
283
285
  return { label: step.label, command: step.command, allowSlow: step.allowSlow ?? null, ok, findings, errors: stepErrors };
284
286
  });
@@ -2,8 +2,8 @@ import { existsSync, readFileSync } from "node:fs";
2
2
  import path from "node:path";
3
3
  import { packageDirectories } from "../system/workspace";
4
4
 
5
- /** A test run or dependency install that a push-gate step reaches, with the chain that led to it. */
6
- export interface StepFinding { kind: "test" | "install"; runner: string; chain: string[] }
5
+ /** A test run, build, or dependency install that a push-gate step reaches, with the chain that led to it. */
6
+ export interface StepFinding { kind: "test" | "build" | "install"; runner: string; chain: string[] }
7
7
  export interface StepResolution { findings: StepFinding[]; errors: string[] }
8
8
 
9
9
  const MAX_DEPTH = 32;
@@ -21,7 +21,7 @@ const TOOLS = {
21
21
  pnpm: tool(["-C", "--dir", "--filter", "-F", "--reporter"], ["--filter", "-F", "--recursive", "-r"]),
22
22
  yarn: tool(["--cwd"]),
23
23
  exec: tool(["-p", "--package", "-c", "--call"]),
24
- turbo: tool(["--filter", "-F", "--concurrency", "--cache-dir", "--output-logs", "--log-order", "--log-prefix", "--env-mode", "--ui", "--cache", "--profile", "--graph", "--summarize"]),
24
+ turbo: tool(["--filter", "-F", "--concurrency", "--cache-dir", "--output-logs", "--log-order", "--log-prefix", "--env-mode", "--ui", "--cache", "--profile", "--graph", "--summarize", "--cwd", "--root-turbo-json", "--heap", "--team", "--token", "--api", "--login", "--trace", "--cpuprofile", "--remote-cache-timeout", "--cache-workers", "--pkg-inference-root"]),
25
25
  } as const;
26
26
  const INSTALLS: Record<"bun" | "npm" | "pnpm" | "yarn", string[]> = {
27
27
  bun: ["install", "i", "add", "a", "update", "remove", "rm"],
@@ -34,10 +34,11 @@ interface Context { root: string; seen: Set<string>; findings: StepFinding[]; er
34
34
 
35
35
  /**
36
36
  * Follow a declared push-gate step through package scripts, shell strings,
37
- * and `agent-tool run-group` plans to every test runner or dependency install
38
- * it reaches. Executables and script files are leaves: their contents are not
39
- * inspected. Workspace filters resolve to every workspace package declaring
40
- * the script, which can over-report but never misses one.
37
+ * and `agent-tool run-group` plans to every test runner, build, or dependency
38
+ * install it reaches. Executables and script files are leaves: their contents
39
+ * are not inspected. Workspace filters resolve to every workspace package
40
+ * declaring the script, which can over-report but never misses one. A command
41
+ * that both builds and tests, such as `cargo test`, is reported once, as a test.
41
42
  */
42
43
  export function resolveStep(root: string, command: string[]): StepResolution {
43
44
  const context: Context = { root, seen: new Set(), findings: [], errors: [] };
@@ -100,20 +101,20 @@ function scripts(directory: string): Record<string, unknown> | null {
100
101
  * arguments appended, then `post<name>`. An unknown name runs `fallback`, the
101
102
  * executable or file of that name, when the manager does so.
102
103
  */
103
- /** Workspace packages from `package.json` workspaces and from pnpm's `pnpm-workspace.yaml`. */
104
- function workspaceDirectories(context: Context): string[] {
105
- const directories = new Set(packageDirectories(context.root));
106
- const file = path.join(context.root, "pnpm-workspace.yaml");
104
+ /** Workspace packages of the workspace rooted at `root` (the repository's by default), from `package.json` workspaces and pnpm's `pnpm-workspace.yaml`. */
105
+ function workspaceDirectories(context: Context, root = context.root): string[] {
106
+ const directories = new Set(packageDirectories(root));
107
+ const file = path.join(root, "pnpm-workspace.yaml");
107
108
  if (!existsSync(file)) return [...directories];
108
109
  let patterns: unknown;
109
110
  try { patterns = (Bun.YAML.parse(readFileSync(file, "utf8")) as { packages?: unknown } | null)?.packages; }
110
- catch (error) { context.errors.push(`Cannot read pnpm-workspace.yaml: ${(error as Error).message}`); return [...directories]; }
111
+ catch (error) { context.errors.push(`Cannot read ${path.relative(context.root, file) || file}: ${(error as Error).message}`); return [...directories]; }
111
112
  const list = (Array.isArray(patterns) ? patterns : []).filter((pattern): pattern is string => typeof pattern === "string");
112
113
  const excluded = list.filter(pattern => pattern.startsWith("!")).map(pattern => new Bun.Glob(pattern.slice(1).replace(/\/$/, "")));
113
114
  for (const pattern of list.filter(pattern => !pattern.startsWith("!"))) {
114
- for (const match of new Bun.Glob(`${pattern.replace(/\/$/, "")}/package.json`).scanSync({ cwd: context.root, onlyFiles: true })) {
115
+ for (const match of new Bun.Glob(`${pattern.replace(/\/$/, "")}/package.json`).scanSync({ cwd: root, onlyFiles: true })) {
115
116
  const relative = path.dirname(match);
116
- if (!match.split("/").includes("node_modules") && !excluded.some(glob => glob.match(relative))) directories.add(path.join(context.root, relative));
117
+ if (!match.split("/").includes("node_modules") && !excluded.some(glob => glob.match(relative))) directories.add(path.join(root, relative));
117
118
  }
118
119
  }
119
120
  return [...directories];
@@ -165,55 +166,220 @@ function visit(context: Context, input: string[], cwd: string, chain: string[],
165
166
  } else if (name === "bun") bun(context, args, cwd, chain, depth, text);
166
167
  else if (name === "bunx" || name === "npx") execute(context, args, cwd, chain, depth);
167
168
  else if (name === "npm" || name === "pnpm" || name === "yarn") packageManager(context, name, args, cwd, chain, depth, text);
168
- else if (name === "turbo") { if (turboTasks(args).some(task => /^test/.test(task.slice(task.lastIndexOf("#") + 1)))) report(context, "test", text, chain); }
169
+ else if (name === "turbo") turbo(context, args, cwd, chain, text);
169
170
  else if (testRunner(name, args)) report(context, "test", text, chain);
171
+ else if (builds(name, args)) report(context, "build", text, chain);
170
172
  else if (["pod", "bundle", "pip", "pip3"].includes(name) && args[0] === "install") report(context, "install", text, chain);
171
173
  else if (name === "bundle" && args[0] === "exec") visit(context, args.slice(1), cwd, chain, depth + 1);
172
174
  }
173
175
 
174
- function turboTasks(args: string[]): string[] {
175
- const rest = args[0] === "run" ? args.slice(1) : args;
176
- const tasks: string[] = [];
177
- for (let index = 0; index < rest.length; index++) {
178
- const value = rest[index]!;
176
+ /* Options, per tool, that take a separate value, so `--profile release` or `-x build` is never read as a subcommand or task. */
177
+ const WEBPACK_VALUES: ReadonlySet<string> = new Set(["-c", "--config", "--config-name", "--env", "--node-env", "--mode", "-o", "--output-path", "--entry", "--name", "-t", "--target", "-d", "--devtool", "--stats"]);
178
+ const DOCKER_VALUES: ReadonlySet<string> = new Set(["--config", "-c", "--context", "-H", "--host", "-l", "--log-level", "--tlscacert", "--tlscert", "--tlskey", "--builder", "-f", "--file", "-p", "--project-name", "--profile", "--env-file", "--project-directory", "--ansi", "--progress", "--parallel"]);
179
+ const GRADLE_VALUES: ReadonlySet<string> = new Set(["-p", "--project-dir", "-x", "--exclude-task", "-b", "--build-file", "-c", "--settings-file", "-g", "--gradle-user-home", "-I", "--init-script", "--include-build", "--project-cache-dir", "--console", "--warning-mode", "--max-workers", "--priority", "--update-locks", "--dependency-verification", "--write-verification-metadata", "--configuration-cache-problems", "--tests", "-D", "-P"]);
180
+ const XCODEBUILD_VALUES: ReadonlySet<string> = new Set(["-project", "-workspace", "-target", "-scheme", "-configuration", "-sdk", "-arch", "-destination", "-destination-timeout", "-xcconfig", "-toolchain", "-derivedDataPath", "-resultBundlePath", "-resultBundleVersion", "-archivePath", "-exportPath", "-exportOptionsPlist", "-clonedSourcePackagesDirPath", "-packageCachePath", "-testPlan", "-only-testing", "-skip-testing", "-only-test-configuration", "-skip-test-configuration", "-xctestrun", "-testProductsPath", "-test-iterations", "-jobs", "-parallel-testing-worker-count", "-maximum-parallel-testing-workers", "-maximum-concurrent-test-device-destinations", "-maximum-concurrent-test-simulator-destinations", "-parallel-testing-enabled", "-test-timeouts-enabled", "-default-test-execution-time-allowance", "-maximum-test-execution-time-allowance", "-test-repetition-relaunch-enabled", "-collect-test-diagnostics", "-localizationPath", "-exportLanguage", "-scmProvider", "-defaultPackageRegistryURL", "-packageDependencySCMToRegistryTransformation", "-authenticationKeyPath", "-authenticationKeyID", "-authenticationKeyIssuerID", "-framework", "-library", "-headers", "-debug-symbols", "-output", "-find-executable", "-find-library"]);
181
+ const RUNNER_VALUES: Record<string, ReadonlySet<string>> = {
182
+ go: new Set(["-C"]), cargo: new Set(["-C", "--config", "-Z", "--color"]), deno: new Set(["--config", "-c"]), swift: new Set(["--package-path"]),
183
+ vite: new Set(["-c", "--config", "--base", "-l", "--logLevel", "-m", "--mode", "--configLoader", "-f", "--filter"]),
184
+ astro: new Set(["--root", "--config", "--site", "--base", "--mode"]),
185
+ webpack: WEBPACK_VALUES, "webpack-cli": WEBPACK_VALUES, docker: DOCKER_VALUES, "docker-compose": DOCKER_VALUES,
186
+ };
187
+
188
+ /** The positional words before any `--`, skipping options and the separate values of those in `takesValue`. */
189
+ function positionals(args: string[], takesValue: ReadonlySet<string>): string[] {
190
+ const words: string[] = [];
191
+ for (let index = 0; index < args.length; index++) {
192
+ const value = args[index]!;
179
193
  if (value === "--") break;
180
- if (value.startsWith("-")) { if (!value.includes("=") && TOOLS.turbo.values.has(value)) index++; continue; }
181
- tasks.push(value);
194
+ if (value.startsWith("-")) { if (takesValue.has(value)) index++; continue; }
195
+ words.push(value);
182
196
  }
183
- return tasks;
197
+ return words;
184
198
  }
185
199
 
186
- /** Global options some runners take before their subcommand: `go -C dir test`, `cargo +nightly -Z flag test`. */
187
- const RUNNER_VALUES: Record<string, string[]> = { go: ["-C"], cargo: ["-C", "--config", "-Z", "--color"], deno: ["--config", "-c"], swift: ["--package-path"] };
200
+ /** The first positional word, after global options such as `go -C dir` or `cargo +nightly -Z flag`. */
188
201
  function subcommand(name: string, args: string[]): string | undefined {
189
- const values = RUNNER_VALUES[name] ?? [];
202
+ const takesValue = RUNNER_VALUES[name] ?? new Set();
190
203
  for (let index = 0; index < args.length; index++) {
191
204
  const value = args[index]!;
192
- if (values.includes(value)) { index++; continue; }
205
+ if (takesValue.has(value)) { index++; continue; }
193
206
  if (value.startsWith("-") || (name === "cargo" && value.startsWith("+"))) continue;
194
207
  return value;
195
208
  }
196
209
  return undefined;
197
210
  }
198
211
 
212
+ /** xcodebuild's actions: positional words other than `NAME=value` build settings. */
213
+ const xcodebuildActions = (args: string[]) => positionals(args, XCODEBUILD_VALUES).filter(word => !word.includes("="));
214
+ /** Gradle task paths such as `test` or `:app:testDebugUnitTest`. */
215
+ const gradleTask = (pattern: string) => new RegExp(`^(?::?[\\w-]+:)*(?:${pattern})$`, "i");
216
+ const GRADLE_TEST = gradleTask("test\\w*");
217
+ const GRADLE_BUILD = gradleTask("assemble\\w*|build(?:Needed|Dependents)?|bundle\\w*|install\\w*");
218
+
199
219
  function testRunner(name: string, args: string[]): boolean {
200
220
  if (["jest", "vitest", "mocha", "ava", "maestro", "detox", "pytest", "rspec"].includes(name)) return true;
201
221
  const first = subcommand(name, args);
202
222
  if (name === "node") return args.some(arg => arg === "--test" || arg.startsWith("--test="));
203
223
  if (["playwright", "deno", "go", "swift"].includes(name)) return first === "test";
204
224
  if (name === "cargo") return first === "test" || first === "nextest";
205
- if (name === "gradle" || name === "gradlew") return args.some(arg => /^(?::?[\w-]+:)*test\w*$/i.test(arg));
206
- if (name === "xcodebuild") return args.some(arg => arg === "test" || arg === "test-without-building");
225
+ if (name === "gradle" || name === "gradlew") return positionals(args, GRADLE_VALUES).some(task => GRADLE_TEST.test(task));
226
+ if (name === "xcodebuild") return xcodebuildActions(args).some(action => action === "test" || action === "test-without-building");
207
227
  if (/^python[\d.]*$/.test(name)) return args[0] === "-m" && args[1] === "pytest";
208
228
  return false;
209
229
  }
210
230
 
231
+ /** webpack-cli subcommands that serve, inspect, or scaffold instead of bundling; any other first word is a build or an entry. */
232
+ const WEBPACK_OTHER = new Set(["serve", "server", "s", "info", "i", "configtest", "t", "version", "v", "help", "h", "init", "create", "new", "c", "n", "loader", "l", "plugin", "p", "migrate", "m"]);
233
+ /** xcodebuild options that only list, report, export, or resolve; without one, xcodebuild builds (its default action). */
234
+ const XCODEBUILD_OTHER = new Set(["-list", "-showBuildSettings", "-showBuildSettingsForIndex", "-showsdks", "-showdestinations", "-showTestPlans", "-version", "-usage", "-help", "-license", "-checkFirstLaunchStatus", "-runFirstLaunch", "-resolvePackageDependencies", "-exportArchive", "-create-xcframework", "-find-executable", "-find-library", "-downloadPlatform", "-downloadAllPlatforms", "-importPlatform"]);
235
+
236
+ /**
237
+ * Bundlers, framework builds, native compilers, and image builds. Static
238
+ * checks are not builds: `tsc` (whether `--noEmit` or `-b`), `cargo
239
+ * check|clippy|fmt`, linters, and formatters.
240
+ */
241
+ function builds(name: string, args: string[]): boolean {
242
+ if (name === "rollup" || name === "tsup") return true;
243
+ if (name === "esbuild") return args.some(arg => arg === "--bundle" || /^--out(?:file|dir)(?:=|$)/.test(arg));
244
+ const first = subcommand(name, args);
245
+ if (name === "webpack" || name === "webpack-cli") return !WEBPACK_OTHER.has(first ?? "");
246
+ if (["vite", "next", "astro", "electrobun", "swift", "go"].includes(name)) return first === "build";
247
+ if (name === "cargo") return ["build", "b", "run", "r"].includes(first ?? "");
248
+ // `expo run:ios|android` compiles the native app before launching it.
249
+ if (name === "expo") return first === "export" || /^(?:export|run):/.test(first ?? "");
250
+ if (name === "gradle" || name === "gradlew") return positionals(args, GRADLE_VALUES).some(task => GRADLE_BUILD.test(task));
251
+ if (name === "xcodebuild") {
252
+ if (args.some(arg => XCODEBUILD_OTHER.has(arg))) return false;
253
+ const actions = xcodebuildActions(args);
254
+ // Without an action, xcodebuild builds.
255
+ return !actions.length || actions.some(action => action !== "clean" && action !== "installsrc");
256
+ }
257
+ if (name === "docker-compose") return first === "build";
258
+ if (name === "docker") {
259
+ const [command, sub] = positionals(args, DOCKER_VALUES);
260
+ return command === "build" || ((command === "image" || command === "builder" || command === "compose") && sub === "build") || (command === "buildx" && ["build", "b", "bake"].includes(sub ?? ""));
261
+ }
262
+ return false;
263
+ }
264
+
265
+ /** turbo's subcommands that run no tasks. */
266
+ const TURBO_COMMANDS = new Set(["prune", "ls", "info", "query", "gen", "generate", "login", "logout", "link", "unlink", "daemon", "telemetry", "bin", "completion", "scan", "boundaries", "devtools", "docs", "config"]);
267
+
268
+ /** The tasks a `turbo` command runs: those after `run` or `watch`, or bare task names. */
269
+ function turboTasks(args: string[]): string[] {
270
+ const words = positionals(args, TOOLS.turbo.values);
271
+ if (words[0] === "run" || words[0] === "watch") return words.slice(1);
272
+ return TURBO_COMMANDS.has(words[0] ?? "") ? [] : words;
273
+ }
274
+
275
+ /** The value of `--name value` or `--name=value` before any `--`. */
276
+ function optionValue(args: string[], name: string): string | undefined {
277
+ for (let index = 0; index < args.length && args[index] !== "--"; index++) {
278
+ const value = args[index]!;
279
+ if (value === name) return args[index + 1];
280
+ if (value.startsWith(`${name}=`)) return value.slice(name.length + 1);
281
+ }
282
+ return undefined;
283
+ }
284
+
285
+ interface TurboConfig { file: string; section: string; tasks: Record<string, unknown>; extends: boolean }
286
+
287
+ function readTurboConfig(context: Context, file: string): TurboConfig | null {
288
+ const relative = path.relative(context.root, file) || file;
289
+ try {
290
+ const value: unknown = Bun.JSONC.parse(readFileSync(file, "utf8"));
291
+ if (!value || typeof value !== "object" || Array.isArray(value)) throw new Error("expected an object");
292
+ // turbo 2 names the section `tasks`; turbo 1 named it `pipeline`.
293
+ const section = "tasks" in value ? "tasks" : "pipeline";
294
+ const tasks = (value as Record<string, unknown>)[section] ?? {};
295
+ if (!tasks || typeof tasks !== "object" || Array.isArray(tasks)) throw new Error(`expected ${section} to be an object`);
296
+ return { file: relative, section, tasks: tasks as Record<string, unknown>, extends: "extends" in value };
297
+ } catch (error) { context.errors.push(`Cannot read ${relative}: ${(error as Error).message}`); return null; }
298
+ }
299
+
300
+ function declaresWorkspaces(directory: string): boolean {
301
+ if (existsSync(path.join(directory, "pnpm-workspace.yaml"))) return true;
302
+ try { return (JSON.parse(readFileSync(path.join(directory, "package.json"), "utf8")) as { workspaces?: unknown }).workspaces !== undefined; } catch { return false; }
303
+ }
304
+
305
+ const turboFile = (directory: string) => ["turbo.json", "turbo.jsonc"].map(name => path.join(directory, name)).find(file => existsSync(file));
306
+
307
+ /**
308
+ * Every turbo configuration that can define a task: the root one, then each
309
+ * workspace package's. The root one is `--root-turbo-json` when given (read
310
+ * from the directory turbo starts in and from the repository root, wherever it
311
+ * exists), else the nearest at or above the directory turbo starts in
312
+ * (`--cwd`) without `extends`.
313
+ */
314
+ function turboConfigs(context: Context, args: string[], cwd: string): TurboConfig[] {
315
+ const loaded = new Map<string, TurboConfig | null>();
316
+ const load = (file: string) => { if (!loaded.has(file)) loaded.set(file, readTurboConfig(context, file)); return loaded.get(file)!; };
317
+ const start = path.resolve(cwd, optionValue(args, "--cwd") ?? ".");
318
+ const explicit = optionValue(args, "--root-turbo-json");
319
+ const roots: string[] = [];
320
+ if (explicit !== undefined) {
321
+ roots.push(...new Set([path.resolve(start, explicit), path.resolve(context.root, explicit)].filter(file => existsSync(file))));
322
+ if (!roots.length) context.errors.push(`Cannot read ${explicit} (--root-turbo-json): no such file.`);
323
+ } else for (let current = start; ; current = path.dirname(current)) {
324
+ const file = turboFile(current);
325
+ if (file && load(file) && !load(file)!.extends) { roots.push(file); break; }
326
+ if (current === context.root || !current.startsWith(`${context.root}${path.sep}`)) break;
327
+ }
328
+ // Packages come from the workspace turbo runs in, the nearest at or above where it starts that declares
329
+ // workspaces, and from the repository's. A workspace root is a workspace directory too, but its
330
+ // turbo.json is a root configuration, not a package's.
331
+ const workspaceRoots = new Set([context.root]);
332
+ for (let current = start; current.startsWith(`${context.root}${path.sep}`); current = path.dirname(current)) {
333
+ if (declaresWorkspaces(current)) { workspaceRoots.add(current); break; }
334
+ }
335
+ const packages = [...workspaceRoots].flatMap(root => workspaceDirectories(context, root).filter(directory => !workspaceRoots.has(directory))).flatMap(directory => turboFile(directory) ?? []);
336
+ return [...new Set([...roots, ...packages])].flatMap(file => load(file) ?? []);
337
+ }
338
+
339
+ /**
340
+ * `turbo run <task...>` runs its tasks and, unless `--only`, every task they
341
+ * depend on in turbo.json: `^name`, `name`, and `package#name` all run tasks
342
+ * named `name`. A dependency's definitions in the root and every package
343
+ * configuration are followed together, which can over-report but never misses
344
+ * one. The package scripts turbo runs for each task are not followed.
345
+ */
346
+ function turbo(context: Context, args: string[], cwd: string, chain: string[], text: string): void {
347
+ const queue = turboTasks(args).map(task => ({ task, hops: [] as string[] }));
348
+ if (!queue.length) return;
349
+ const separator = args.indexOf("--");
350
+ const configs = (separator === -1 ? args : args.slice(0, separator)).includes("--only") ? [] : turboConfigs(context, args, cwd);
351
+ const found: Partial<Record<"test" | "build", string[]>> = {};
352
+ const seen = new Set<string>();
353
+ while (queue.length) {
354
+ const { task, hops } = queue.shift()!;
355
+ const name = task.slice(task.lastIndexOf("#") + 1);
356
+ if (seen.has(name)) continue;
357
+ seen.add(name);
358
+ if (/^test/.test(name)) found.test ??= hops;
359
+ else if (/^build/.test(name)) found.build ??= hops;
360
+ for (const config of configs) {
361
+ for (const [key, definition] of Object.entries(config.tasks)) {
362
+ if (key.slice(key.lastIndexOf("#") + 1) !== name) continue;
363
+ const dependsOn = (definition as { dependsOn?: unknown } | null)?.dependsOn;
364
+ // `$TURBO_EXTENDS$` and turbo 1's `$ENV` entries name no task.
365
+ for (const dependency of Array.isArray(dependsOn) ? dependsOn : []) {
366
+ if (typeof dependency === "string" && !dependency.startsWith("$")) queue.push({ task: dependency.replace(/^\^/, ""), hops: [...hops, `${config.file} ${config.section}.${key}.dependsOn: ${dependency}`] });
367
+ }
368
+ }
369
+ }
370
+ }
371
+ const kind = found.test ? "test" : found.build ? "build" : null;
372
+ if (kind) context.findings.push({ kind, runner: text, chain: [...(chain.at(-1) === text ? chain : [...chain, text]), ...found[kind]!] });
373
+ }
374
+
211
375
  function bun(context: Context, args: string[], cwd: string, chain: string[], depth: number, text: string): void {
212
376
  const { rest, seen } = options(args, TOOLS.bun);
213
377
  const directory = directoryOption(cwd, seen);
214
378
  const sub = rest[0];
215
379
  if (!sub) return;
216
380
  if (sub === "test") report(context, "test", text, chain);
381
+ // The bundler is built in, so `bun build` never runs a package script of that name.
382
+ else if (sub === "build") report(context, "build", text, chain);
217
383
  else if (INSTALLS.bun.includes(sub)) report(context, "install", text, chain);
218
384
  else if (sub === "x") execute(context, rest.slice(1), directory, chain, depth);
219
385
  else if (sub === "exec") { if (rest[1]) visitShell(context, rest[1], directory, chain, depth + 1); }