@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.
@@ -0,0 +1,303 @@
1
+ import { spawnSync } from "node:child_process";
2
+ import { existsSync, mkdtempSync, readFileSync, realpathSync, rmSync, writeFileSync, writeSync } from "node:fs";
3
+ import { isatty } from "node:tty";
4
+ import { tmpdir } from "node:os";
5
+ import path from "node:path";
6
+ import { executeGroup, reraiseGroupSignal, type GroupRecord } from "../commands/group";
7
+ import { loadConfig, PUSH_GATE_BUDGET_SECONDS, type AgentToolConfig } from "../config";
8
+ import { gitEnvironment } from "../git/environment";
9
+ import { checkPermissions, installedPermissionHarness } from "../permissions/install";
10
+ import { checkSkills, installedSkillHarnesses } from "../skills/install";
11
+ import { branchErrors, parsePrePushInput, pushedBranches, zeroOid, type PushTuple } from "./branch";
12
+ import { binariesAddedByCommits, commitFindings, rejectedBinaries } from "./checks";
13
+ import { assert, checkoutRoot, git, output } from "./core";
14
+ import { checkHooks } from "./hooks";
15
+ import { resolveStep, type StepFinding } from "./pushGateSteps";
16
+
17
+ export const PRE_PUSH_SOURCE = "scripts/git/hooks/pre-push";
18
+ export const PUSH_GATE_ENV = "AGENT_TOOL_PUSH_GATE";
19
+
20
+ /** The one canonical pre-push body; `push-gate check` requires the tracked hook to match it byte for byte. */
21
+ export const PUSH_GATE_HOOK = `#!/bin/sh
22
+ # Generated by \`agent-tool push-gate hook\`; \`agent-tool push-gate check\` fails
23
+ # when this file differs from it. Declare push checks in agent-tool.json's
24
+ # pushGate section instead of editing this file.
25
+ set -eu
26
+ root=$(git rev-parse --show-toplevel)
27
+ cd "$root"
28
+ # GUI Git clients can start hooks without mise's shims on PATH.
29
+ if command -v bun >/dev/null 2>&1; then
30
+ bun=$(command -v bun)
31
+ elif command -v mise >/dev/null 2>&1 && bun=$(mise which bun 2>/dev/null) && [ -x "$bun" ]; then
32
+ # Declared steps run bun by name too.
33
+ PATH="\${bun%/*}:$PATH"
34
+ export PATH
35
+ else
36
+ echo "pre-push: bun is not on PATH and mise cannot provide it. Install the Bun" >&2
37
+ echo "this repository pins (mise install), or put bun on PATH, then push again." >&2
38
+ exit 1
39
+ fi
40
+ cli="$root/node_modules/@a2f0/agent-tool/src/index.ts"
41
+ if [ ! -f "$cli" ]; then
42
+ echo "pre-push: $cli is missing; install this repository's dependencies first." >&2
43
+ exit 1
44
+ fi
45
+ exec "$bun" "$cli" push-gate run --pre-push "$@"
46
+ `;
47
+
48
+ export type PushScan = "deleted" | "since-remote-tip" | "new-on-remote" | "unknown-remote-tip";
49
+ /** A pushed ref with the commits the push adds, as exposed to declared steps. */
50
+ export interface PushedRef extends PushTuple {
51
+ deleted: boolean;
52
+ scan: PushScan;
53
+ reason: string;
54
+ revisions: string[];
55
+ commits: string[];
56
+ base: string | null;
57
+ range: string | null;
58
+ }
59
+
60
+ /** The destination as Git names it; `advertised` counts the commits it advertises that this clone has, null when its refs could not be listed. */
61
+ export interface PushDestination { name: string | null; url: string; advertised: number | null; error: string | null }
62
+
63
+ /**
64
+ * Hide credentials a URL carries (`https://user:token@host/...`) before it is
65
+ * printed or handed to steps. An ssh user name alone is kept.
66
+ */
67
+ export function redactUrl(value: string): string {
68
+ return value.replace(/([a-z][a-z0-9+.-]*:\/\/)([^/@\s]+)@/gi, (_, scheme: string, userinfo: string) => /^ssh:/i.test(scheme) && !userinfo.includes(":") ? `${scheme}${userinfo}@` : `${scheme}***@`);
69
+ }
70
+
71
+ const fullOid = /^(?:[a-f0-9]{40}|[a-f0-9]{64})$/;
72
+ const LIST_TIMEOUT_MS = 60_000;
73
+ function gitWithInput(args: string[], input: string): { status: number | null; stdout: string; stderr: string } {
74
+ const result = spawnSync("git", args, { input, encoding: "utf8", env: gitEnvironment(), maxBuffer: 256 * 1024 * 1024 });
75
+ if (result.error) throw result.error;
76
+ return { status: result.status, stdout: result.stdout, stderr: result.stderr };
77
+ }
78
+
79
+ /**
80
+ * What the destination already has: every commit its refs point to (branches,
81
+ * tags, and host refs such as GitHub's pull refs) that also exists in this
82
+ * clone, from one `git ls-remote` of the URL Git is pushing to. Tracking refs
83
+ * are not used: they record a past fetch, possibly of another repository after
84
+ * `git remote set-url`, so subtracting them could skip commits the
85
+ * destination lacks.
86
+ */
87
+ export function listDestination(remote: string, pushUrl: string, list = true): PushDestination & { commits: string[] } {
88
+ const configured = /^[a-zA-Z0-9][a-zA-Z0-9._-]*$/.test(remote) && spawnSync("git", ["remote", "get-url", remote], { stdio: "ignore", env: gitEnvironment() }).status === 0;
89
+ const name = configured ? remote : null;
90
+ // Only the redacted URL is reported; the real one is used to list refs.
91
+ const url = redactUrl(pushUrl);
92
+ if (!list) return { name, url, advertised: null, error: null, commits: [] };
93
+ assert(!pushUrl.startsWith("-"), "The push URL must not start with '-'.");
94
+ // Never prompt for credentials or wait forever: a failed listing falls back to the old tip Git reported.
95
+ const listed = spawnSync("git", ["ls-remote", pushUrl], { encoding: "utf8", stdio: ["ignore", "pipe", "pipe"], env: { ...gitEnvironment(), GIT_TERMINAL_PROMPT: "0" }, maxBuffer: 256 * 1024 * 1024, timeout: LIST_TIMEOUT_MS, killSignal: "SIGKILL" });
96
+ if (listed.error || listed.status !== 0) return { name, url, advertised: null, error: redactUrl(listed.stderr || listed.error?.message || "git ls-remote failed").replaceAll(pushUrl, url).trim(), commits: [] };
97
+ const candidates = [...new Set(listed.stdout.split("\n").map(line => line.split("\t", 1)[0]!).filter(oid => fullOid.test(oid)))];
98
+ if (!candidates.length) return { name, url, advertised: 0, error: null, commits: [] };
99
+ const checked = gitWithInput(["cat-file", "--batch-check=%(objectname) %(objecttype)"], candidates.map(oid => `${oid}^{commit}`).join("\n") + "\n");
100
+ assert(checked.status === 0, `Could not inspect the destination's advertised commits: ${checked.stderr.trim()}`);
101
+ const commits = [...new Set(checked.stdout.split("\n").filter(line => line.endsWith(" commit")).map(line => line.split(" ", 1)[0]!))];
102
+ return { name, url, advertised: commits.length, error: null, commits };
103
+ }
104
+
105
+ const isCommit = (value: string) => spawnSync("git", ["cat-file", "-e", `${value}^{commit}`], { stdio: "ignore", env: gitEnvironment() }).status === 0;
106
+
107
+ /**
108
+ * The commits each pushed ref adds: those its new tip reaches that no commit
109
+ * the destination already has reaches, as Git itself decides what to send.
110
+ * The remote's old tip counts when this clone has it, even if listing failed.
111
+ * A destination with nothing this clone has, such as a new or unrelated
112
+ * repository, gets the whole branch scanned: over-scanning is noise,
113
+ * under-scanning lets an unchecked commit through. `base` is the remote's old
114
+ * tip when known, else the newest commit the destination has when there is
115
+ * exactly one, else null.
116
+ */
117
+ export function pushedRefs(tuples: PushTuple[], destination: { commits: string[]; advertised: number | null; error: string | null }): PushedRef[] {
118
+ return tuples.map(tuple => {
119
+ if (zeroOid(tuple.localOid)) return { ...tuple, deleted: true, scan: "deleted", reason: "A deletion pushes no commits.", revisions: [], commits: [], base: null, range: null };
120
+ assert(isCommit(tuple.localOid), `${tuple.localRef} (${tuple.localOid}) is not a commit; push-gate checks commits only.`);
121
+ const knownTip = !zeroOid(tuple.remoteOid) && isCommit(tuple.remoteOid);
122
+ const scan: PushScan = zeroOid(tuple.remoteOid) ? "new-on-remote" : knownTip ? "since-remote-tip" : "unknown-remote-tip";
123
+ const excluded = [...new Set([...destination.commits, ...(knownTip ? [tuple.remoteOid] : [])])];
124
+ const listed = gitWithInput(["rev-list", "--boundary", tuple.localOid, "--stdin"], excluded.map(oid => `^${oid}\n`).join(""));
125
+ assert(listed.status === 0, `Could not list the commits ${tuple.remoteRef} adds: ${listed.stderr.trim()}`);
126
+ const lines = listed.stdout.split("\n").filter(Boolean);
127
+ const commits = lines.filter(line => !line.startsWith("-"));
128
+ const boundary = lines.filter(line => line.startsWith("-")).map(line => line.slice(1));
129
+ let base = knownTip ? git(["rev-parse", `${tuple.remoteOid}^{commit}`]) : null;
130
+ if (!base) {
131
+ const independent = boundary.length > 1 ? git(["merge-base", "--independent", ...boundary]).split("\n").filter(Boolean) : boundary;
132
+ base = independent.length === 1 ? independent[0]! : null;
133
+ }
134
+ const tip = scan === "since-remote-tip" ? "the remote's old tip and " : scan === "unknown-remote-tip" ? "not the remote's old tip, which this clone lacks, but " : "";
135
+ const reason = destination.error !== null
136
+ ? `Could not list the destination's refs (${destination.error}); ${knownTip ? "excludes only the remote's old tip" : "scans the whole branch"}.`
137
+ : `Excludes ${tip}the ${destination.advertised} commit(s) the destination advertises that this clone has.`;
138
+ // The boundary selects the same commits as the full exclusion list, in a short argument list.
139
+ const revisions = commits.length ? [tuple.localOid, ...(boundary.length ? ["--not", ...boundary] : [])] : [tuple.localOid, "--not", tuple.localOid];
140
+ return { ...tuple, deleted: false, scan, reason, revisions, commits, base, range: base ? `${base}..${tuple.localOid}` : tuple.localOid };
141
+ });
142
+ }
143
+
144
+ /** Git exports variables such as GIT_DIR to hooks; steps that build fixture repositories must not inherit them. */
145
+ export function clearLocalGitEnvironment(): void {
146
+ for (const name of git(["rev-parse", "--local-env-vars"]).split("\n").filter(Boolean)) delete process.env[name];
147
+ }
148
+
149
+ interface Guard { name: string; ref?: string; ok: boolean; durationMs: number; details?: unknown; error?: string }
150
+
151
+ function guard(guards: Guard[], name: string, ref: string | undefined, check: () => { ok: boolean; details?: unknown }): void {
152
+ const started = performance.now();
153
+ let result: Omit<Guard, "name" | "durationMs">;
154
+ try { const value = check(); result = { ok: value.ok, ...(value.ok || value.details === undefined ? {} : { details: value.details }) }; }
155
+ catch (error) { result = { ok: false, error: (error as Error).message }; }
156
+ guards.push({ name, ...(ref ? { ref } : {}), ...result, durationMs: Math.round(performance.now() - started) });
157
+ }
158
+
159
+ /** The built-in trust guards, from the same implementations as `hooks check`, `skills check`, `permissions check`, `branch check --pre-push`, `commits check`, and `checks binaries`. */
160
+ function runGuards(root: string, config: AgentToolConfig, tuples: PushTuple[], destination: ReturnType<typeof listDestination>): { guards: Guard[]; refs: PushedRef[] } {
161
+ const guards: Guard[] = [];
162
+ guard(guards, "hooks", undefined, () => { const result = checkHooks(); return { ok: result.ok, details: { changes: result.changes.filter(change => change.status !== "unchanged"), blockers: result.blockers, configure: result.configure } }; });
163
+ const skills = installedSkillHarnesses(root);
164
+ if (skills) guard(guards, "skills", undefined, () => { const changes = skills.flatMap(harness => checkSkills(root, harness)).filter(change => change.status !== "unchanged"); return { ok: !changes.length, details: { harnesses: skills, changes } }; });
165
+ const permissions = installedPermissionHarness(root);
166
+ if (permissions) guard(guards, "permissions", undefined, () => { const changes = checkPermissions(root, permissions).filter(change => change.status !== "unchanged"); return { ok: !changes.length, details: { harness: permissions, changes } }; });
167
+ guard(guards, "branch", undefined, () => { const branches = pushedBranches(tuples).map(name => ({ name, errors: branchErrors(name, config) })).filter(branch => branch.errors.length); return { ok: !branches.length, details: { branches } }; });
168
+ let refs: PushedRef[] = [];
169
+ guard(guards, "ranges", undefined, () => { refs = pushedRefs(tuples, destination); return { ok: true }; });
170
+ for (const ref of refs.filter(item => !item.deleted)) {
171
+ guard(guards, "commits", ref.remoteRef, () => { const findings = commitFindings(ref.commits, config); return { ok: !findings.length, details: { checked: ref.commits.length, findings } }; });
172
+ guard(guards, "binaries", ref.remoteRef, () => { const rejected = rejectedBinaries(binariesAddedByCommits(ref.commits), config); return { ok: !rejected.length, details: { rejected } }; });
173
+ }
174
+ return { guards, refs };
175
+ }
176
+
177
+ function worktreeState(refs: PushedRef[]): { headOid: string; matchesPush: boolean; differences: string[] } {
178
+ const headOid = git(["rev-parse", "HEAD"]);
179
+ const differences: string[] = [];
180
+ for (const ref of refs.filter(item => !item.deleted)) {
181
+ const commit = git(["rev-parse", `${ref.localOid}^{commit}`]);
182
+ if (commit !== headOid) differences.push(`${ref.remoteRef} receives ${commit}, but HEAD is ${headOid}.`);
183
+ }
184
+ if (git(["status", "--porcelain=v1", "--untracked-files=normal"])) differences.push("The working tree has uncommitted or untracked changes.");
185
+ return { headOid, matchesPush: !differences.length, differences };
186
+ }
187
+
188
+ const seconds = (ms: number) => `${(ms / 1000).toFixed(1)}s`;
189
+ const say = (message: string) => writeSync(2, `push-gate: ${message}\n`);
190
+
191
+ export async function runPushGate(args: string[], root: string): Promise<number> {
192
+ assert(args.length === 3 && args[0] === "--pre-push" && !!args[1] && !!args[2], "Usage: push-gate run --pre-push <remote> <url>");
193
+ // The remote argument is a URL, credentials and all, when the push named no remote.
194
+ const [, remote, url] = args as [string, string, string];
195
+ const started = performance.now();
196
+ assert(!isatty(0), "push-gate run reads the refs being pushed from stdin; run it through git push.");
197
+ const tuples = parsePrePushInput(readFileSync(0, "utf8"));
198
+ const config = loadConfig(root);
199
+ const gate = config.pushGate;
200
+ const notes: string[] = [];
201
+ if (!gate) notes.push("agent-tool.json declares no pushGate section; only the built-in guards ran.");
202
+ // Deletions alone push nothing, so they need no listing of the destination.
203
+ const destination = listDestination(remote, url, tuples.some(tuple => !zeroOid(tuple.localOid)));
204
+ const { commits: _advertised, ...remoteInfo } = destination;
205
+ const { guards, refs } = runGuards(root, config, tuples, destination);
206
+ const failed = guards.filter(item => !item.ok);
207
+ for (const item of failed) {
208
+ const detail = item.error ?? JSON.stringify(item.details);
209
+ say(`${item.name}${item.ref ? ` (${item.ref})` : ""} failed: ${detail.length > 600 ? `${detail.slice(0, 600)}… (see the JSON report)` : detail}`);
210
+ }
211
+ const budgetSeconds = gate?.budgetSeconds ?? PUSH_GATE_BUDGET_SECONDS;
212
+ const summary = (group: { record: GroupRecord; report: string } | null, worktree: ReturnType<typeof worktreeState> | null) => {
213
+ const elapsedMs = Math.round(performance.now() - started);
214
+ const steps = group?.record.steps.map(step => ({ label: step.label, status: step.status, durationMs: step.receipt?.durationMs ?? null, log: step.receipt?.log ?? null })) ?? [];
215
+ const slowest = steps.filter(step => step.durationMs !== null).sort((a, b) => b.durationMs! - a.durationMs!).slice(0, 3).map(step => ({ label: step.label, durationMs: step.durationMs! }));
216
+ const exceeded = elapsedMs > budgetSeconds * 1000;
217
+ const guardMs = guards.reduce((sum, item) => sum + item.durationMs, 0);
218
+ const warnings: string[] = [];
219
+ if (exceeded) warnings.push(`The push gate took ${seconds(elapsedMs)}, over its ${budgetSeconds}s budget (pushGate.budgetSeconds). ${slowest.length ? `Slowest steps: ${slowest.map(step => `${step.label} ${seconds(step.durationMs)}`).join(", ")}. Move them to CI.` : `The built-in guards took ${seconds(guardMs)}.`}`);
220
+ if (worktree && !worktree.matchesPush) warnings.push(`The declared steps checked the working tree, which is not what this push sends (${worktree.differences.join(" ")}) CI checks the pushed commits and is the authority.`);
221
+ for (const warning of warnings) say(warning);
222
+ const ok = !failed.length && (!group || group.record.status === "passed");
223
+ output({
224
+ ok, remote: remoteInfo,
225
+ refs: refs.map(({ commits, ...ref }) => ({ ...ref, commits: commits.length })),
226
+ guards, steps: group ? { report: group.report, status: group.record.status, durationMs: group.record.durationMs, error: group.record.error, steps } : null,
227
+ worktree, budget: { seconds: budgetSeconds, elapsedMs, exceeded, slowest }, notes, warnings,
228
+ });
229
+ };
230
+ if (failed.length) { summary(null, null); return 1; }
231
+ const steps = gate?.steps ?? [];
232
+ if (!steps.length || refs.every(ref => ref.deleted)) {
233
+ if (steps.length) notes.push(refs.length ? "This push only deletes refs; the declared steps did not run." : "Git passed no refs to push; the declared steps did not run.");
234
+ summary(null, null); return 0;
235
+ }
236
+ const worktree = worktreeState(refs);
237
+ const directory = mkdtempSync(path.join(tmpdir(), "agent-tool-push-gate-"));
238
+ let result: Awaited<ReturnType<typeof executeGroup>>;
239
+ try {
240
+ const context = path.join(directory, "push.json");
241
+ writeFileSync(context, `${JSON.stringify({ schemaVersion: 1, remote: remoteInfo, headOid: worktree.headOid, worktreeMatchesPush: worktree.matchesPush, refs }, null, 2)}\n`, { mode: 0o600, flag: "wx" });
242
+ process.env[PUSH_GATE_ENV] = context;
243
+ say(`running ${steps.length} declared step(s): ${steps.map(step => step.label).join(", ")}`);
244
+ result = await executeGroup({ label: "push-gate", steps: steps.map(({ label, command }) => ({ label, command })) }, (record, report) => summary({ record, report }, worktree));
245
+ } finally {
246
+ // Removed before any signal is re-raised, which ends the process.
247
+ delete process.env[PUSH_GATE_ENV];
248
+ rmSync(directory, { recursive: true, force: true });
249
+ }
250
+ return reraiseGroupSignal(result);
251
+ }
252
+
253
+ export interface PushGateCheck {
254
+ ok: boolean;
255
+ hook: { path: string; tracked: boolean; canonical: boolean | null; installed: boolean };
256
+ pushGate: { declared: boolean; budgetSeconds: number | null };
257
+ steps: { label: string; command: string[]; allowSlow: string | null; ok: boolean; findings: StepFinding[]; errors: string[] }[];
258
+ errors: string[];
259
+ notes: string[];
260
+ }
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. */
263
+ export function checkPushGate(root: string, config: AgentToolConfig): PushGateCheck {
264
+ const errors: string[] = [], notes: string[] = [];
265
+ const tracked = spawnSync("git", ["ls-files", "--error-unmatch", "--", PRE_PUSH_SOURCE], { cwd: root, stdio: "ignore", env: gitEnvironment() }).status === 0;
266
+ const file = path.join(root, PRE_PUSH_SOURCE);
267
+ const canonical = tracked && existsSync(file) ? readFileSync(file, "utf8") === PUSH_GATE_HOOK : tracked ? false : null;
268
+ const installed = config.hooks.files.some(entry => entry.source === PRE_PUSH_SOURCE && entry.target === "pre-push" && entry.executable);
269
+ const gate = config.pushGate;
270
+ if (!gate && !tracked) {
271
+ notes.push(`No push gate: agent-tool.json has no pushGate section and ${PRE_PUSH_SOURCE} is not tracked.`);
272
+ return { ok: true, hook: { path: PRE_PUSH_SOURCE, tracked, canonical, installed }, pushGate: { declared: false, budgetSeconds: null }, steps: [], errors, notes };
273
+ }
274
+ if (!gate) errors.push(`${PRE_PUSH_SOURCE} is tracked, but agent-tool.json declares no pushGate section; declare one, even with no steps.`);
275
+ if (!tracked) errors.push(`pushGate is declared, but ${PRE_PUSH_SOURCE} is not tracked; commit the output of \`agent-tool push-gate hook\` there.`);
276
+ else if (!canonical) errors.push(`${PRE_PUSH_SOURCE} differs from \`agent-tool push-gate hook\`; replace it with that output byte for byte.`);
277
+ if (!installed) errors.push(`hooks.files does not install ${PRE_PUSH_SOURCE} as an executable pre-push: add { "source": "${PRE_PUSH_SOURCE}", "target": "pre-push", "executable": true }.`);
278
+ const steps = (gate?.steps ?? []).map(step => {
279
+ const { findings, errors: stepErrors } = resolveStep(root, step.command);
280
+ 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.`);
282
+ for (const error of stepErrors) errors.push(`Step '${step.label}': ${error}`);
283
+ return { label: step.label, command: step.command, allowSlow: step.allowSlow ?? null, ok, findings, errors: stepErrors };
284
+ });
285
+ return { ok: !errors.length, hook: { path: PRE_PUSH_SOURCE, tracked, canonical, installed }, pushGate: { declared: !!gate, budgetSeconds: gate?.budgetSeconds ?? null }, steps, errors, notes };
286
+ }
287
+
288
+ /** `push-gate hook` needs no repository; `run` resolves the root before clearing Git's hook environment. */
289
+ export async function pushGateCommand(args: string[]): Promise<number> {
290
+ const action = args.shift();
291
+ if (action === "hook") { assert(!args.length, "Usage: push-gate hook"); writeSync(1, PUSH_GATE_HOOK); return 0; }
292
+ if (action === "check") {
293
+ assert(!args.length, "Usage: push-gate check");
294
+ const root = checkoutRoot(); process.chdir(root);
295
+ const result = checkPushGate(root, loadConfig(root));
296
+ output(result); return result.ok ? 0 : 1;
297
+ }
298
+ assert(action === "run", "Usage: push-gate hook | check | run --pre-push <remote> <url>");
299
+ const root = checkoutRoot(); process.chdir(root);
300
+ clearLocalGitEnvironment();
301
+ assert(realpathSync(checkoutRoot()) === realpathSync(root), `Without Git's hook environment the repository resolves elsewhere than ${root}; run push-gate from the checkout.`);
302
+ return runPushGate(args, root);
303
+ }