@a2f0/agent-tool 0.1.56 → 0.1.58
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/README.md +3 -2
- package/package.json +1 -1
- package/skills/ship-pr/SKILL.md +58 -25
- package/skills/squash-merge/SKILL.md +16 -10
- package/src/cli.ts +6 -0
- package/src/commands/group.ts +25 -12
- package/src/config.ts +34 -0
- package/src/permissions/catalog.ts +2 -2
- package/src/permissions/install.ts +8 -0
- package/src/skills/bundled.ts +2 -2
- package/src/skills/install.ts +14 -0
- package/src/workflows/baseHealth.ts +165 -0
- package/src/workflows/branch.ts +19 -5
- package/src/workflows/checks.ts +36 -5
- package/src/workflows/hooks.ts +27 -6
- package/src/workflows/pr.ts +72 -15
- package/src/workflows/prFreshness.ts +2 -1
- package/src/workflows/pushGate.ts +303 -0
- package/src/workflows/pushGateSteps.ts +386 -0
- package/src/workflows/repository.ts +2 -0
|
@@ -0,0 +1,165 @@
|
|
|
1
|
+
import { loadConfig, type RequiredCheck } from "../config";
|
|
2
|
+
import { assert, json, nativeBranch, option, output, read, repository } from "./core";
|
|
3
|
+
|
|
4
|
+
/** The health of a branch's tip: one of four closed states. */
|
|
5
|
+
export type BaseHealthStatus = "green" | "red" | "pending" | "no-ci";
|
|
6
|
+
export type Outcome = "passing" | "failing" | "pending";
|
|
7
|
+
|
|
8
|
+
export interface WorkflowRun { id: number; workflowId: number; name: string; headSha: string; status: string; conclusion: string | null; url: string; createdAt: string }
|
|
9
|
+
export interface CheckRun { name: string; status: string; conclusion: string | null; url: string | null }
|
|
10
|
+
export interface Job { id: number; name: string; status: string; conclusion: string | null; url: string }
|
|
11
|
+
export interface MergedPull { number: number; title: string; url: string; headRefOid: string; mergeCommit: { oid: string } | null }
|
|
12
|
+
export interface OpenPull { number: number; title: string; body: string; url: string }
|
|
13
|
+
export interface RangeCommit { sha: string; message: string }
|
|
14
|
+
|
|
15
|
+
export const DEFAULT_LIMIT = 30;
|
|
16
|
+
const PASSING = ["success", "skipped", "neutral"];
|
|
17
|
+
|
|
18
|
+
/** A finished run passes only with success, skipped, or neutral; cancelled, timed-out, and every other conclusion fail. */
|
|
19
|
+
export function outcome(status: string, conclusion: string | null): Outcome {
|
|
20
|
+
if (status !== "completed") return "pending";
|
|
21
|
+
return conclusion !== null && PASSING.includes(conclusion) ? "passing" : "failing";
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
/** Runs order by creation time, then by id, which GitHub assigns increasingly, for runs created in the same second. */
|
|
25
|
+
const newer = (a: WorkflowRun, b: WorkflowRun) => a.createdAt > b.createdAt || (a.createdAt === b.createdAt && a.id > b.id);
|
|
26
|
+
|
|
27
|
+
/**
|
|
28
|
+
* Each workflow's most recent push run on the branch. A workflow whose path
|
|
29
|
+
* filters skipped the tip keeps the state of its last run, so a docs-only
|
|
30
|
+
* merge neither hides nor clears a failure.
|
|
31
|
+
*/
|
|
32
|
+
export function latestRuns(runs: WorkflowRun[]): WorkflowRun[] {
|
|
33
|
+
const latest = new Map<number, WorkflowRun>();
|
|
34
|
+
for (const run of runs) {
|
|
35
|
+
const current = latest.get(run.workflowId);
|
|
36
|
+
if (!current || newer(run, current)) latest.set(run.workflowId, run);
|
|
37
|
+
}
|
|
38
|
+
return [...latest.values()].sort((a, b) => a.name.localeCompare(b.name));
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
export interface RequiredState { name: string; workflow: string | null; outcome: Outcome | "missing"; conclusion: string | null; url: string | null }
|
|
42
|
+
|
|
43
|
+
/** Required checks as reported on the tip; a check absent there (a PR-only job, a path filter) is `missing` and decides nothing. */
|
|
44
|
+
export function requiredStates(required: RequiredCheck[], checkRuns: CheckRun[], runs: WorkflowRun[]): RequiredState[] {
|
|
45
|
+
const workflowOf = (url: string | null) => { const id = url?.match(/\/actions\/runs\/(\d+)\//)?.[1]; return id ? runs.find(run => String(run.id) === id)?.name ?? null : null; };
|
|
46
|
+
return required.map(check => {
|
|
47
|
+
// Runs of the configured workflow and runs that cannot be attributed to a listed push run (another event,
|
|
48
|
+
// another app, a run past the window) both count; only runs known to belong to another workflow are left out.
|
|
49
|
+
const matches = checkRuns.filter(run => run.name === check.name && (check.workflow === undefined || [check.workflow, null].includes(workflowOf(run.url))));
|
|
50
|
+
if (!matches.length) return { name: check.name, workflow: check.workflow ?? null, outcome: "missing", conclusion: null, url: null };
|
|
51
|
+
// Several apps or events can report the same name: any failure fails it, then any unfinished run keeps it pending.
|
|
52
|
+
const outcomes = matches.map(run => outcome(run.status, run.conclusion));
|
|
53
|
+
const worst = matches[outcomes.indexOf("failing")] ?? matches[outcomes.indexOf("pending")] ?? matches[0]!;
|
|
54
|
+
return { name: check.name, workflow: check.workflow ?? null, outcome: outcome(worst.status, worst.conclusion), conclusion: worst.conclusion, url: worst.url };
|
|
55
|
+
});
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
/** Any failure makes the tip red; otherwise a branch without push runs has no CI, and unfinished runs keep it pending. */
|
|
59
|
+
export function classify(workflows: Outcome[], required: (Outcome | "missing")[]): BaseHealthStatus {
|
|
60
|
+
if ([...workflows, ...required].includes("failing")) return "red";
|
|
61
|
+
if (!workflows.length) return "no-ci";
|
|
62
|
+
if ([...workflows, ...required].includes("pending")) return "pending";
|
|
63
|
+
return "green";
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
/** The latest passing run of the same workflow created before the failing one, if the window holds one. */
|
|
67
|
+
export function lastGreen(runs: WorkflowRun[], failing: WorkflowRun): WorkflowRun | null {
|
|
68
|
+
return runs.filter(run => run.workflowId === failing.workflowId && newer(failing, run) && outcome(run.status, run.conclusion) === "passing")
|
|
69
|
+
.sort((a, b) => newer(a, b) ? -1 : newer(b, a) ? 1 : 0)[0] ?? null;
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
export interface Merge { oid: string; subject: string; pr: { number: number; title: string | null; url: string | null; headOid: string | null } | null }
|
|
73
|
+
|
|
74
|
+
/** Name the PR behind each commit in the breaking range: by merge commit, else by the `(#123)` or merge-commit subject. */
|
|
75
|
+
export function breakingMerges(commits: RangeCommit[], merged: MergedPull[]): Merge[] {
|
|
76
|
+
return commits.map(commit => {
|
|
77
|
+
const subject = commit.message.split("\n", 1)[0]!;
|
|
78
|
+
const pull = merged.find(item => item.mergeCommit?.oid === commit.sha);
|
|
79
|
+
if (pull) return { oid: commit.sha, subject, pr: { number: pull.number, title: pull.title, url: pull.url, headOid: pull.headRefOid } };
|
|
80
|
+
const number = subject.match(/\(#(\d+)\)$/)?.[1] ?? subject.match(/^Merge pull request #(\d+)/)?.[1];
|
|
81
|
+
return { oid: commit.sha, subject, pr: number ? { number: Number(number), title: null, url: null, headOid: null } : null };
|
|
82
|
+
});
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
/** Open PRs whose title or body cites a failing run or job by URL or id, so a second session does not duplicate a repair. */
|
|
86
|
+
export function openRepairs(pulls: OpenPull[], failing: { runId: number; jobIds: number[] }[]): { number: number; title: string; url: string; references: string[] }[] {
|
|
87
|
+
const ids = failing.flatMap(item => [String(item.runId), ...item.jobIds.map(String)]);
|
|
88
|
+
return pulls.flatMap(pull => {
|
|
89
|
+
const text = `${pull.title}\n${pull.body ?? ""}`;
|
|
90
|
+
const references = ids.filter(id => new RegExp(`(?:^|[^0-9])${id}(?![0-9])`).test(text));
|
|
91
|
+
return references.length ? [{ number: pull.number, title: pull.title, url: pull.url, references }] : [];
|
|
92
|
+
});
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
export interface FailingJob { workflow: string | null; runId: number | null; runUrl: string | null; headOid: string; job: string; jobId: number | null; url: string | null; conclusion: string | null }
|
|
96
|
+
|
|
97
|
+
const encode = (value: string) => value.split("/").map(encodeURIComponent).join("/");
|
|
98
|
+
|
|
99
|
+
export function baseHealthCommand(args: string[]): number {
|
|
100
|
+
const branchOption = option(args, "--branch");
|
|
101
|
+
const limitOption = option(args, "--limit");
|
|
102
|
+
assert(!args.length, "Usage: repo base-health [--branch <name>] [--limit <n>]");
|
|
103
|
+
const limit = Number(limitOption ?? DEFAULT_LIMIT);
|
|
104
|
+
assert(Number.isSafeInteger(limit) && limit >= 1 && limit <= 100, "--limit must be an integer from 1 to 100.");
|
|
105
|
+
const repo = repository();
|
|
106
|
+
const branch = branchOption ?? repo.defaultBranchRef.name;
|
|
107
|
+
assert(nativeBranch(branch), `Invalid branch name '${branch}'.`);
|
|
108
|
+
const name = repo.nameWithOwner;
|
|
109
|
+
const tip = json<{ sha: string }>(["api", `repos/${name}/branches/${encode(branch)}`, "--jq", "{sha: .commit.sha}"]).sha;
|
|
110
|
+
assert(/^[a-f0-9]{40,64}$/.test(tip), `Could not read the tip of ${name}:${branch}.`);
|
|
111
|
+
const runs = json<WorkflowRun[]>(["api", `repos/${name}/actions/runs?branch=${encodeURIComponent(branch)}&event=push&per_page=${limit}`, "--jq", "[.workflow_runs[] | {id, workflowId: .workflow_id, name, headSha: .head_sha, status, conclusion, url: .html_url, createdAt: .created_at}]"]);
|
|
112
|
+
assert(Array.isArray(runs), "Could not list workflow runs.");
|
|
113
|
+
const required = loadConfig().merge.requiredChecks;
|
|
114
|
+
// Every page, one entry per line, so a failing required check is never past the first page. Required
|
|
115
|
+
// checks are check runs or, for external CI, commit status contexts; the combined status keeps each context's latest.
|
|
116
|
+
const lines = (args: string[]) => read("gh", args).split("\n").filter(Boolean).map(line => JSON.parse(line) as CheckRun);
|
|
117
|
+
const checkRuns: CheckRun[] = required.length ? [
|
|
118
|
+
...lines(["api", "--paginate", `repos/${name}/commits/${tip}/check-runs?per_page=100`, "--jq", ".check_runs[] | {name, status, conclusion, url: .html_url}"]),
|
|
119
|
+
...lines(["api", "--paginate", `repos/${name}/commits/${tip}/status?per_page=100`, "--jq", '.statuses[] | {name: .context, status: (if .state == "pending" then "in_progress" else "completed" end), conclusion: (if .state == "success" then "success" elif .state == "pending" then null else .state end), url: .target_url}']),
|
|
120
|
+
] : [];
|
|
121
|
+
const latest = latestRuns(runs);
|
|
122
|
+
const requiredChecks = requiredStates(required, checkRuns, runs);
|
|
123
|
+
const workflows = latest.map(run => ({ name: run.name, runId: run.id, url: run.url, headOid: run.headSha, onTip: run.headSha === tip, status: run.status, conclusion: run.conclusion, outcome: outcome(run.status, run.conclusion) }));
|
|
124
|
+
const status = classify(workflows.map(item => item.outcome), requiredChecks.map(item => item.outcome));
|
|
125
|
+
const notes: string[] = [];
|
|
126
|
+
const tipHasRuns = runs.some(run => run.headSha === tip);
|
|
127
|
+
if (status === "no-ci") notes.push(`No push-triggered workflow ran on ${branch} within the last ${limit} runs; this repository lacks CI on pushes to it.`);
|
|
128
|
+
else if (!tipHasRuns) notes.push(`No push run has started on the tip yet, or path filters skipped it; workflows show their latest run on ${branch}.`);
|
|
129
|
+
const failingRuns = latest.filter(run => outcome(run.status, run.conclusion) === "failing");
|
|
130
|
+
const failingJobs: FailingJob[] = failingRuns.flatMap(run => read("gh", ["api", "--paginate", `repos/${name}/actions/runs/${run.id}/jobs?per_page=100`, "--jq", ".jobs[] | {id, name, status, conclusion, url: .html_url}"]).split("\n").filter(Boolean).map(line => JSON.parse(line) as Job)
|
|
131
|
+
.filter(job => outcome(job.status, job.conclusion) === "failing")
|
|
132
|
+
.map(job => ({ workflow: run.name, runId: run.id, runUrl: run.url, headOid: run.headSha, job: job.name, jobId: job.id, url: job.url, conclusion: job.conclusion })));
|
|
133
|
+
// A failing required check outside those runs (another app, or a run beyond the window) is listed by its own link.
|
|
134
|
+
for (const check of requiredChecks.filter(item => item.outcome === "failing" && !failingJobs.some(job => job.url === item.url))) {
|
|
135
|
+
failingJobs.push({ workflow: check.workflow, runId: null, runUrl: null, headOid: tip, job: check.name, jobId: null, url: check.url, conclusion: check.conclusion });
|
|
136
|
+
}
|
|
137
|
+
let green: { oid: string; workflows: string[] } | null = null;
|
|
138
|
+
let breakingRange: { from: string; to: string; merges: Merge[]; truncated: boolean } | null = null;
|
|
139
|
+
let repairs: ReturnType<typeof openRepairs> = [];
|
|
140
|
+
if (status === "red") {
|
|
141
|
+
const greens = failingRuns.map(run => ({ run, green: lastGreen(runs, run) }));
|
|
142
|
+
if (greens.length && greens.every(item => item.green)) {
|
|
143
|
+
// The oldest of the failing workflows' last green runs starts a range that covers all of them.
|
|
144
|
+
const oldest = greens.map(item => item.green!).sort((a, b) => newer(a, b) ? 1 : newer(b, a) ? -1 : 0)[0]!;
|
|
145
|
+
green = { oid: oldest.headSha, workflows: failingRuns.map(run => run.name) };
|
|
146
|
+
const compare = json<{ commits: RangeCommit[] }>(["api", `repos/${name}/compare/${oldest.headSha}...${tip}`, "--jq", "{commits: [.commits[] | {sha, message: .commit.message}]}"]);
|
|
147
|
+
const merged = json<MergedPull[]>(["pr", "list", "-R", name, "--state", "merged", "--base", branch, "--limit", String(limit), "--json", "number,title,url,headRefOid,mergeCommit"]);
|
|
148
|
+
breakingRange = { from: oldest.headSha, to: tip, merges: breakingMerges(compare.commits.slice(0, limit), merged), truncated: compare.commits.length > limit };
|
|
149
|
+
} else if (failingRuns.length) notes.push(`No passing run of ${greens.filter(item => !item.green).map(item => item.run.name).join(", ")} within the last ${limit} push runs; raise --limit to find the breaking range.`);
|
|
150
|
+
const pulls = json<OpenPull[]>(["pr", "list", "-R", name, "--state", "open", "--limit", String(limit), "--json", "number,title,body,url"]);
|
|
151
|
+
// A failing required check outside the listed runs still names its run and job in its link.
|
|
152
|
+
const cited = new Map<number, number[]>(failingRuns.map(run => [run.id, []]));
|
|
153
|
+
for (const job of failingJobs) {
|
|
154
|
+
const link = job.url?.match(/\/actions\/runs\/(\d+)(?:\/job\/(\d+))?/);
|
|
155
|
+
const runId = job.runId ?? (link ? Number(link[1]) : null);
|
|
156
|
+
const jobId = job.jobId ?? (link?.[2] ? Number(link[2]) : null);
|
|
157
|
+
if (runId === null) continue;
|
|
158
|
+
if (!cited.has(runId)) cited.set(runId, []);
|
|
159
|
+
if (jobId !== null) cited.get(runId)!.push(jobId);
|
|
160
|
+
}
|
|
161
|
+
repairs = openRepairs(pulls, [...cited].map(([runId, jobIds]) => ({ runId, jobIds })));
|
|
162
|
+
}
|
|
163
|
+
output({ repo: name, branch, status, tip: { oid: tip, hasRuns: tipHasRuns }, inProgress: workflows.some(item => item.outcome === "pending"), workflows, requiredChecks, failingJobs, lastGreen: green, breakingRange, openRepairs: repairs, limit, notes });
|
|
164
|
+
return 0;
|
|
165
|
+
}
|
package/src/workflows/branch.ts
CHANGED
|
@@ -15,6 +15,24 @@ export function branchErrors(name: string, config: AgentToolConfig): string[] {
|
|
|
15
15
|
return errors;
|
|
16
16
|
}
|
|
17
17
|
|
|
18
|
+
/** One line of Git's pre-push stdin: `<local ref> <local oid> <remote ref> <remote oid>`. */
|
|
19
|
+
export interface PushTuple { localRef: string; localOid: string; remoteRef: string; remoteOid: string }
|
|
20
|
+
const fullOid = /^(?:[a-f0-9]{40}|[a-f0-9]{64})$/i;
|
|
21
|
+
export const zeroOid = (value: string) => /^0+$/.test(value);
|
|
22
|
+
|
|
23
|
+
export function parsePrePushInput(source: string): PushTuple[] {
|
|
24
|
+
return source.split("\n").filter(line => line.trim()).map(line => {
|
|
25
|
+
const fields = line.trim().split(/\s+/);
|
|
26
|
+
assert(fields.length === 4 && fullOid.test(fields[1]!) && fullOid.test(fields[3]!), "Malformed Git pre-push input.");
|
|
27
|
+
return { localRef: fields[0]!, localOid: fields[1]!, remoteRef: fields[2]!, remoteOid: fields[3]! };
|
|
28
|
+
});
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
/** Branch names a push creates or updates; deletions and tags are skipped. */
|
|
32
|
+
export function pushedBranches(tuples: PushTuple[]): string[] {
|
|
33
|
+
return tuples.flatMap(tuple => zeroOid(tuple.localOid) || !tuple.remoteRef.startsWith("refs/heads/") ? [] : [tuple.remoteRef.slice("refs/heads/".length)]);
|
|
34
|
+
}
|
|
35
|
+
|
|
18
36
|
export function remoteUrl(remote: string, push = false): string {
|
|
19
37
|
assert(/^[a-zA-Z0-9][a-zA-Z0-9._-]*$/.test(remote), "Expected a named Git remote.");
|
|
20
38
|
const urls = git(["remote", "get-url", ...(push ? ["--push"] : []), "--all", remote]).split("\n");
|
|
@@ -29,11 +47,7 @@ export function branchCommand(args: string[]): number {
|
|
|
29
47
|
const prePush = flag(args, "--pre-push");
|
|
30
48
|
assert(!prePush || !args.length, "--pre-push reads destination refs from stdin and accepts no names.");
|
|
31
49
|
assert(!args.some(arg => arg.startsWith("-")), "Usage: branch check [name...]");
|
|
32
|
-
const names = prePush ? readFileSync(0, "utf8")
|
|
33
|
-
const fields = line.trim().split(/\s+/);
|
|
34
|
-
assert(fields.length === 4 && /^(?:[a-f0-9]{40}|[a-f0-9]{64})$/i.test(fields[1]!) && /^(?:[a-f0-9]{40}|[a-f0-9]{64})$/i.test(fields[3]!), "Malformed Git pre-push input.");
|
|
35
|
-
return /^0+$/.test(fields[1]!) || !fields[2]!.startsWith("refs/heads/") ? [] : [fields[2]!.slice("refs/heads/".length)];
|
|
36
|
-
}) : args.length ? args : [currentBranch()];
|
|
50
|
+
const names = prePush ? pushedBranches(parsePrePushInput(readFileSync(0, "utf8"))) : args.length ? args : [currentBranch()];
|
|
37
51
|
const results = names.map(name => ({ name, errors: branchErrors(name, config) }));
|
|
38
52
|
const ok = results.every(result => !result.errors.length);
|
|
39
53
|
output({ ok, branches: results }); return ok ? 0 : 1;
|
package/src/workflows/checks.ts
CHANGED
|
@@ -30,8 +30,13 @@ export function commitsCommand(args: string[]): number {
|
|
|
30
30
|
const remote = option(args, "--exclude-remotes");
|
|
31
31
|
assert(!remote || /^[a-zA-Z0-9][a-zA-Z0-9._-]*$/.test(remote), "--exclude-remotes requires a named remote.");
|
|
32
32
|
assert(action === "check" && !!range && !range.startsWith("-") && !args.length, "Usage: commits check --range <revision-range>");
|
|
33
|
-
const config = loadConfig();
|
|
34
33
|
const commits = git(["rev-list", range, ...(excludes.length || remote ? ["--not", ...excludes, ...(remote ? [`--remotes=${remote}`] : [])] : []), "--"]).split("\n").filter(Boolean);
|
|
34
|
+
const findings = commitFindings(commits, loadConfig());
|
|
35
|
+
output({ ok: !findings.length, range, checked: commits.length, findings }); return findings.length ? 1 : 0;
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
/** Signature, attribution, and subject policy for each listed commit; only failing commits are returned. */
|
|
39
|
+
export function commitFindings(commits: string[], config: AgentToolConfig): { commit: string; errors: string[] }[] {
|
|
35
40
|
const findings: { commit: string; errors: string[] }[] = [];
|
|
36
41
|
for (const commit of commits) {
|
|
37
42
|
const errors: string[] = [];
|
|
@@ -48,7 +53,7 @@ export function commitsCommand(args: string[]): number {
|
|
|
48
53
|
}
|
|
49
54
|
if (errors.length) findings.push({ commit, errors });
|
|
50
55
|
}
|
|
51
|
-
|
|
56
|
+
return findings;
|
|
52
57
|
}
|
|
53
58
|
|
|
54
59
|
/** Parse NUL-delimited --numstat; rename records carry an empty path then old/new. */
|
|
@@ -79,12 +84,38 @@ export function binariesCommand(args: string[]): number {
|
|
|
79
84
|
const base = candidates.find(ref => spawnSync("git", ["rev-parse", "--verify", "--quiet", `${ref}^{commit}`], { stdio: "ignore" }).status === 0);
|
|
80
85
|
assert(base, "No upstream/base ref is available; pass --range explicitly."); revisions = [`${base}...HEAD`];
|
|
81
86
|
}
|
|
82
|
-
const files =
|
|
83
|
-
const
|
|
84
|
-
const rejected = files.filter(file => !allowed.some(pattern => pattern.match(file)));
|
|
87
|
+
const files = diffBinaries(revisions);
|
|
88
|
+
const rejected = rejectedBinaries(files, loadConfig());
|
|
85
89
|
output({ ok: !rejected.length, binaries: files, rejected }); return rejected.length ? 1 : 0;
|
|
86
90
|
}
|
|
87
91
|
|
|
92
|
+
function diffBinaries(revisions: string[]): string[] {
|
|
93
|
+
return binaryPaths(git(["diff", "--no-ext-diff", "--no-textconv", "--numstat", "-z", "--diff-filter=ACMRT", ...revisions, "--"]));
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
export function rejectedBinaries(files: string[], config: AgentToolConfig): string[] {
|
|
97
|
+
const allowed = config.binaries.allow.map(pattern => new Bun.Glob(pattern));
|
|
98
|
+
return files.filter(file => !allowed.some(pattern => pattern.match(file)));
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
/**
|
|
102
|
+
* Binary files the listed commits introduce. A commit is compared with its
|
|
103
|
+
* parent; a merge only reports paths that differ from every parent, the
|
|
104
|
+
* content the merge itself adds, so files a parent already carried are not
|
|
105
|
+
* counted twice.
|
|
106
|
+
*/
|
|
107
|
+
export function binariesAddedByCommits(commits: string[]): string[] {
|
|
108
|
+
const found = new Set<string>();
|
|
109
|
+
let emptyTree: string | undefined;
|
|
110
|
+
for (const commit of commits) {
|
|
111
|
+
const parents = git(["rev-list", "--parents", "-n", "1", commit, "--"]).split(" ").slice(1);
|
|
112
|
+
if (!parents.length) { emptyTree ??= git(["hash-object", "-t", "tree", "--stdin"]); for (const file of diffBinaries([emptyTree, commit])) found.add(file); continue; }
|
|
113
|
+
const perParent = parents.map(parent => new Set(diffBinaries([parent, commit])));
|
|
114
|
+
for (const file of perParent[0]!) if (perParent.every(set => set.has(file))) found.add(file);
|
|
115
|
+
}
|
|
116
|
+
return [...found].sort();
|
|
117
|
+
}
|
|
118
|
+
|
|
88
119
|
export interface GatePolicy { required?: string[]; allowSkipped?: string[]; conditional?: { job: string; source: string; output: string }[] }
|
|
89
120
|
export function evaluateGate(needs: unknown, policy: GatePolicy = {}): { ok: boolean; errors: string[] } {
|
|
90
121
|
assert(needs && typeof needs === "object" && !Array.isArray(needs), "Needs must be an object of GitHub job results.");
|
package/src/workflows/hooks.ts
CHANGED
|
@@ -22,11 +22,31 @@ function resolveDirectory(directory: string): string {
|
|
|
22
22
|
}
|
|
23
23
|
function within(parent: string, child: string): boolean { const relative = path.relative(parent, child); return !relative || (!relative.startsWith(`..${path.sep}`) && relative !== ".." && !path.isAbsolute(relative)); }
|
|
24
24
|
|
|
25
|
+
export interface HooksCheck { ok: boolean; applied: false; destination: string; configure?: boolean; changes: { target: string; status: string }[]; blockers: string[] }
|
|
26
|
+
|
|
27
|
+
/** The read-only `hooks check` result, shared with the push gate's guard. */
|
|
28
|
+
export function checkHooks(): HooksCheck {
|
|
29
|
+
const plan = planHooks(false);
|
|
30
|
+
return plan.empty ? plan.report : { ok: plan.ok, applied: false, destination: plan.destination, configure: plan.configure, changes: plan.changes, blockers: plan.blockers };
|
|
31
|
+
}
|
|
32
|
+
|
|
25
33
|
export function hooksCommand(args: string[]): number {
|
|
26
34
|
const action = args.shift();
|
|
27
35
|
const apply = flag(args, "--apply");
|
|
28
36
|
const adopt = flag(args, "--adopt");
|
|
29
37
|
assert((action === "install" || action === "check") && !args.length && (action === "install" || (!apply && !adopt)), "Usage: hooks install [--apply] [--adopt] | hooks check");
|
|
38
|
+
const plan = planHooks(adopt);
|
|
39
|
+
if (plan.empty) { output(plan.report); return 0; }
|
|
40
|
+
const { common, destination, sources, manifestFile, changes, blockers, configure, ok } = plan;
|
|
41
|
+
if (action === "check" || !apply) {
|
|
42
|
+
output({ ok, applied: false, destination, configure, changes, blockers });
|
|
43
|
+
return action === "check" && !ok || blockers.length ? 1 : 0;
|
|
44
|
+
}
|
|
45
|
+
install(plan.root, common, destination, sources, manifestFile, changes, blockers, configure);
|
|
46
|
+
return 0;
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
function planHooks(adopt: boolean) {
|
|
30
50
|
const root = realpathSync(git(["rev-parse", "--show-toplevel"]));
|
|
31
51
|
const common = resolveDirectory(git(["rev-parse", "--path-format=absolute", "--git-common-dir"]));
|
|
32
52
|
const worktreeConfig = config(["--local", "--bool", "--get", "extensions.worktreeConfig"]) === "true";
|
|
@@ -45,7 +65,7 @@ export function hooksCommand(args: string[]): number {
|
|
|
45
65
|
// A configured destination inside the checkout must not contain tracked files.
|
|
46
66
|
if (within(root, destination)) assert(!git(["ls-files", "--", path.relative(root, destination)]), "Hook destination contains tracked files.");
|
|
47
67
|
const manifestFile = path.join(destination, manifestName);
|
|
48
|
-
if (!entries.length && !present(manifestFile)) {
|
|
68
|
+
if (!entries.length && !present(manifestFile)) return { empty: true as const, report: { ok: true, applied: false as const, destination, changes: [], blockers: [] } };
|
|
49
69
|
let previous: Manifest = { schemaVersion: 1, files: {} };
|
|
50
70
|
if (present(manifestFile)) {
|
|
51
71
|
assert(lstatSync(manifestFile).isFile(), "Hook ownership manifest must be a regular file.");
|
|
@@ -75,10 +95,11 @@ export function hooksCommand(args: string[]): number {
|
|
|
75
95
|
}
|
|
76
96
|
const configure = destination !== effective;
|
|
77
97
|
const ok = !blockers.length && changes.every(change => change.status === "unchanged") && !configure;
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
98
|
+
return { empty: false as const, root, common, destination, sources, manifestFile, changes, blockers, configure, ok };
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
type HookSource = { source: string; target: string; executable: boolean; hash: string };
|
|
102
|
+
function install(root: string, common: string, destination: string, sources: HookSource[], manifestFile: string, changes: { target: string; status: string }[], blockers: string[], configure: boolean): void {
|
|
82
103
|
assert(!blockers.length, blockers.join("\n"));
|
|
83
104
|
mkdirSync(destination, { recursive: true });
|
|
84
105
|
const backupDirectory = path.join(destination, `.agent-tool-backup-${randomUUID()}`);
|
|
@@ -108,5 +129,5 @@ export function hooksCommand(args: string[]): number {
|
|
|
108
129
|
if (configure) assert(spawnSync("git", ["config", "--local", "core.hooksPath", destination], { stdio: "inherit" }).status === 0, "Could not configure installed hooks.");
|
|
109
130
|
const after = config(["--type=path", "--get", "core.hooksPath"]);
|
|
110
131
|
assert(resolveDirectory(after ? path.resolve(root, after) : path.join(common, "hooks")) === destination, "Effective hooksPath does not match installation; inspect Git configuration.");
|
|
111
|
-
output({ ok: true, applied: true, destination, changes, backups });
|
|
132
|
+
output({ ok: true, applied: true, destination, changes, backups });
|
|
112
133
|
}
|
package/src/workflows/pr.ts
CHANGED
|
@@ -65,25 +65,75 @@ export function failedJobLogs(pr: { prNumber: string; repo: string }, expected:
|
|
|
65
65
|
return failed;
|
|
66
66
|
}
|
|
67
67
|
|
|
68
|
-
|
|
69
|
-
|
|
68
|
+
/** GitHub computes mergeability after the base moves; wait briefly instead of failing on UNKNOWN. */
|
|
69
|
+
function readyPullRequest(identity: { prNumber: string; repo: string }, attempts = 5, delayMs = 2000): PullRequest {
|
|
70
|
+
let pr = pullRequest(identity.prNumber, identity.repo);
|
|
71
|
+
for (let attempt = 1; attempt < attempts && (pr.mergeable === "UNKNOWN" || pr.mergeStateStatus === "UNKNOWN"); attempt++) {
|
|
72
|
+
Bun.sleepSync(delayMs);
|
|
73
|
+
pr = pullRequest(identity.prNumber, identity.repo);
|
|
74
|
+
}
|
|
75
|
+
return pr;
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
function notReady(pr: PullRequest, baseBranch: string, strict: boolean): string {
|
|
79
|
+
const state = `${pr.state}/${pr.mergeable}/${pr.mergeStateStatus}`;
|
|
80
|
+
if (pr.mergeable === "CONFLICTING" || pr.mergeStateStatus === "DIRTY") return `PR conflicts with ${baseBranch} (${state}); integrate the base, resolve the conflict, validate, review, and push again.`;
|
|
81
|
+
if (pr.mergeStateStatus === "BEHIND") return strict
|
|
82
|
+
? `PR is behind ${baseBranch} (${state}); integrate the base, validate, review, and push again.`
|
|
83
|
+
: `GitHub still requires an up-to-date branch (${state}) although merge.requireStrictBaseFreshness is false; integrate the base, or turn off the up-to-date requirement in ${baseBranch}'s protection or ruleset.`;
|
|
84
|
+
if (pr.mergeable === "UNKNOWN" || pr.mergeStateStatus === "UNKNOWN") return `GitHub has not computed mergeability yet (${state}); run preflight again shortly.`;
|
|
85
|
+
return `PR is not ready to merge (${state}).`;
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
/**
|
|
89
|
+
* Read-only merge readiness. `reviewedBase` is the base the review covered,
|
|
90
|
+
* or null for `pr merge`, which supplies the base it just fetched as
|
|
91
|
+
* `fetchedLiveBase`. With `merge.requireStrictBaseFreshness` the live base
|
|
92
|
+
* must equal the reviewed one and the head must contain it. Without it a base
|
|
93
|
+
* that moved since review is accepted: the reviewed head is still the PR head,
|
|
94
|
+
* its checks pass, GitHub reports no conflict, and configured package versions
|
|
95
|
+
* must still be current against the live base, since two merges taking the
|
|
96
|
+
* same version would leave the second unpublishable.
|
|
97
|
+
*/
|
|
98
|
+
export function preflight(expectedHead: string, baseBranch: string, reviewedBase: string | null, fetchedLiveBase?: string): unknown {
|
|
99
|
+
oid(expectedHead); if (reviewedBase !== null) oid(reviewedBase); clean();
|
|
70
100
|
assert(head() === expectedHead, "Local HEAD differs from reviewed HEAD.");
|
|
101
|
+
const config = loadConfig();
|
|
102
|
+
const strict = config.merge.requireStrictBaseFreshness;
|
|
71
103
|
const identity = resolvePr();
|
|
72
|
-
const pr =
|
|
104
|
+
const pr = readyPullRequest(identity);
|
|
73
105
|
assert(pr.headRefOid === expectedHead && pr.headRefName === currentBranch(), "PR does not match the current branch and reviewed HEAD.");
|
|
74
|
-
assert(pr.state === "OPEN" && !pr.isDraft && pr.mergeable === "MERGEABLE" && pr.mergeStateStatus === "CLEAN",
|
|
106
|
+
assert(pr.state === "OPEN" && !pr.isDraft && pr.mergeable === "MERGEABLE" && pr.mergeStateStatus === "CLEAN", notReady(pr, baseBranch, strict));
|
|
75
107
|
const target = resolvePullRequestMergeTarget(identity, baseBranch);
|
|
76
108
|
assert(target.headOid === expectedHead, "PR head changed during preflight.");
|
|
77
|
-
|
|
78
|
-
assert(
|
|
79
|
-
const
|
|
80
|
-
if (
|
|
109
|
+
const liveBase = fetchedLiveBase ?? remoteBranchHead(resolveRepositoryGitUrl(identity.repo), baseBranch);
|
|
110
|
+
assert(liveBase, `Could not read the live ${baseBranch} branch of ${identity.repo}.`);
|
|
111
|
+
const baseOid = reviewedBase ?? liveBase;
|
|
112
|
+
if (strict) {
|
|
113
|
+
assert(liveBase === baseOid, "Live base differs from reviewed base; integrate, validate and review again.");
|
|
114
|
+
assert(git(["merge-base", expectedHead, baseOid]) === baseOid, "Reviewed HEAD does not include the reviewed base.");
|
|
115
|
+
assertStrictBaseFreshness(identity.repo, baseBranch);
|
|
116
|
+
} else if (reviewedBase !== null) {
|
|
117
|
+
assert(git(["merge-base", expectedHead, reviewedBase]) === reviewedBase, "Reviewed HEAD does not include the reviewed base.");
|
|
118
|
+
}
|
|
81
119
|
const checks = checkSnapshot(identity, expectedHead);
|
|
82
120
|
assert(checks.ok, checks.reason ?? "Checks have not passed.");
|
|
83
121
|
// Explicit version policy opts in; unversioned repositories need no manifest.
|
|
84
|
-
if (config.versions.packages !== null)
|
|
122
|
+
if (config.versions.packages !== null) {
|
|
123
|
+
const versionBase = strict ? baseOid : liveBase;
|
|
124
|
+
// Preflight is read-only, so it never fetches; `pr merge` fetched the live base before calling it.
|
|
125
|
+
assert(versionBase === baseOid || spawnSync("git", ["cat-file", "-e", `${versionBase}^{commit}`], { stdio: "ignore", env: gitEnvironment() }).status === 0, `The live ${baseBranch} ${versionBase} moved since review and is not in this clone; fetch it with \`agent-tool repo context --fetch\`, then run preflight again to check package versions against it.`);
|
|
126
|
+
assert(planVersions(process.cwd(), versionBase).every(plan => plan.headVersion === plan.targetVersion), strict || versionBase === reviewedBase
|
|
127
|
+
? "Package versions are stale against the reviewed base."
|
|
128
|
+
: `Package versions are stale against the live ${baseBranch} ${versionBase}; another merge took this version. Integrate the base, prepare versions, validate, and review again.`);
|
|
129
|
+
// A merge that landed while checks were read may have taken the same version; check against it instead.
|
|
130
|
+
if (!strict) {
|
|
131
|
+
const settled = remoteBranchHead(resolveRepositoryGitUrl(identity.repo), baseBranch);
|
|
132
|
+
assert(settled === liveBase, `The live ${baseBranch} moved from ${liveBase} to ${settled || "nothing"} during preflight; run it again so package versions are checked against the new base.`);
|
|
133
|
+
}
|
|
134
|
+
}
|
|
85
135
|
assert(head() === expectedHead, "Local HEAD changed during preflight.");
|
|
86
|
-
return { ok: true, repo: identity.repo, pr: pr.number, url: pr.url, headOid: expectedHead, baseBranch, baseOid, checks: checks.checks };
|
|
136
|
+
return { ok: true, repo: identity.repo, pr: pr.number, url: pr.url, headOid: expectedHead, baseBranch, baseOid, liveBaseOid: liveBase, baseMoved: liveBase !== baseOid, strictBaseFreshness: strict, checks: checks.checks };
|
|
87
137
|
}
|
|
88
138
|
|
|
89
139
|
/**
|
|
@@ -96,7 +146,9 @@ export function mergeReviewedHead(rootDir: string, subject: string | undefined,
|
|
|
96
146
|
assert(!!expectedHead && !!baseBranch, "Merge requires a reviewed HEAD and a base branch.");
|
|
97
147
|
const identity = resolvePr();
|
|
98
148
|
const baseOid = resolveFreshBaseRef(identity.repo, baseBranch);
|
|
99
|
-
|
|
149
|
+
// Under the strict policy the fetched base is the one the head must contain; otherwise it is only the live base.
|
|
150
|
+
const strict = loadConfig(rootDir).merge.requireStrictBaseFreshness;
|
|
151
|
+
try { preflight(expectedHead, baseBranch, strict ? baseOid : null, baseOid); }
|
|
100
152
|
catch (error) { throw new Error(`Refusing to merge: preflight failed against live ${baseBranch} ${baseOid}: ${(error as Error).message}`); }
|
|
101
153
|
// Bind the merge to the branch that passed preflight, so a retarget in between is refused.
|
|
102
154
|
return squashMerge(rootDir, subject, expectedHead, baseBranch);
|
|
@@ -180,9 +232,11 @@ export async function prWorkflowCommand(args: string[]): Promise<number> {
|
|
|
180
232
|
assert(expected && !args.length, "Usage: pr cancel-runs --head <oid>"); oid(expected);
|
|
181
233
|
const identity = resolvePr(); const pr = pullRequest(identity.prNumber, identity.repo);
|
|
182
234
|
assert(!pr.isCrossRepository, "Cancelling runs supports same-repository PRs only.");
|
|
183
|
-
// The current head's runs are its only CI; cancel them only once it can no longer merge as is
|
|
235
|
+
// The current head's runs are its only CI; cancel them only once it can no longer merge as is,
|
|
236
|
+
// which happens only under the strict policy: otherwise a head behind its base still merges.
|
|
184
237
|
const base = pr.headRefOid === expected ? baseFreshness(identity.repo, expected, pr.baseRefName) : null;
|
|
185
238
|
assert(!base || base.behind, "This is the PR's current head and it contains its live base; cancelling would leave it without CI.");
|
|
239
|
+
assert(!base || loadConfig().merge.requireStrictBaseFreshness, "This is the PR's current head; without merge.requireStrictBaseFreshness it merges although its base moved, so cancelling would leave it without CI.");
|
|
186
240
|
const result = cancelRuns(identity.repo, pr.headRefName, expected);
|
|
187
241
|
output({ ...identity, headOid: expected, currentHead: pr.headRefOid, ...(base ? { base } : {}), ...result }); return result.ok ? 0 : 1;
|
|
188
242
|
}
|
|
@@ -190,7 +244,10 @@ export async function prWorkflowCommand(args: string[]): Promise<number> {
|
|
|
190
244
|
const wait = flag(args, "--wait");
|
|
191
245
|
const allowBehind = flag(args, "--allow-behind");
|
|
192
246
|
const expected = option(args, "--head") ?? head();
|
|
193
|
-
const
|
|
247
|
+
const { merge } = loadConfig();
|
|
248
|
+
const options = timeoutOptions(args, merge.checksTimeoutSeconds);
|
|
249
|
+
// Without the strict policy a head behind its base still merges, so its CI is worth waiting for.
|
|
250
|
+
const stopBehind = merge.requireStrictBaseFreshness && !allowBehind;
|
|
194
251
|
assert(!args.length, "Usage: pr checks [--wait] [--head <oid>] [--allow-behind] [--timeout seconds] [--interval seconds]"); oid(expected);
|
|
195
252
|
const identity = resolvePr();
|
|
196
253
|
const compared = new Map<string, Map<string, number>>();
|
|
@@ -202,8 +259,8 @@ export async function prWorkflowCommand(args: string[]): Promise<number> {
|
|
|
202
259
|
const branch = pr.baseRefName;
|
|
203
260
|
if (!compared.has(branch)) compared.set(branch, new Map());
|
|
204
261
|
const base = baseFreshness(identity.repo, expected, branch, compared.get(branch));
|
|
205
|
-
//
|
|
206
|
-
if (base.behind &&
|
|
262
|
+
// Under the strict policy a head behind its base cannot ship as reviewed, so waiting on its CI only spends runner time.
|
|
263
|
+
if (base.behind && stopBehind) return { done: true, value: { ...value, ok: false, waiting: false, behind: true, base, reason: behindReason(base, expected) } };
|
|
207
264
|
return { done: !value.waiting, value: { ...value, behind: base.behind, base } };
|
|
208
265
|
};
|
|
209
266
|
const result = wait ? await poll(inspect, options) : inspect().value;
|
|
@@ -24,8 +24,9 @@ export function baseFreshness(repo: string, head: string, branch: string, cache
|
|
|
24
24
|
return { branch, liveOid, behindBy, behind: behindBy > 0 };
|
|
25
25
|
}
|
|
26
26
|
|
|
27
|
+
/** Only repositories that set `merge.requireStrictBaseFreshness` stop for a head behind its base. */
|
|
27
28
|
export function behindReason(base: BaseFreshness, head: string): string {
|
|
28
|
-
return `PR head is ${base.behindBy} commit(s) behind ${base.branch} at ${base.liveOid}
|
|
29
|
+
return `PR head is ${base.behindBy} commit(s) behind ${base.branch} at ${base.liveOid}, and merge.requireStrictBaseFreshness requires the live base: integrate the base, validate, review, and push, then cancel this head's runs with \`agent-tool pr cancel-runs --head ${head}\`.`;
|
|
29
30
|
}
|
|
30
31
|
|
|
31
32
|
const ACTIVE = ["queued", "in_progress", "waiting", "requested", "pending"];
|