Skip to content

Open-source Grok Bot alternative with a virtual machine that bots can use

Pre-push checks only what a push changes, in seconds (#4415)

Milind Soni119858a4d283
diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md
index 268161a50d..7d020f69e9 100644
--- a/CONTRIBUTING.md
+++ b/CONTRIBUTING.md
@@ -278,7 +278,7 @@ For eligible owner runs on Boat, the static job also runs the selected Linux
test lanes; their logs appear in groups named for each lane. Fork PRs use
GitHub-hosted jobs. See [Linux on Boat](docs/ci.md#linux-on-boat).
-A `pre-push` hook installed by `pnpm install` runs lint, typecheck and the locale check before a push (about a minute). `git push --no-verify` skips it once; `OMB_SKIP_HOOKS=1` skips it for a session.
+A `pre-push` hook installed by `pnpm install` checks the files a push changes, in seconds: lint, the locale check when a catalog changed, and the size and vocabulary guards when a source they read changed. Typecheck and the suite stay in CI. A checkout without dependencies checks nothing and lets the push go. `git push --no-verify` skips it once; `OMB_SKIP_HOOKS=1` skips it for a session.
Provider fakes under `server/testing/fake-*.ts` must stay dependency-free: they run as bare subprocesses and at least one is copied out of the repo by a test, so a relative import from the repo dies at link time. `server/testing/fakes-self-contained.test.ts` enforces it.
diff --git a/scripts/git-hooks/pre-push b/scripts/git-hooks/pre-push
index 71ee7956f5..4d54eaa40f 100755
--- a/scripts/git-hooks/pre-push
+++ b/scripts/git-hooks/pre-push
@@ -1,20 +1,17 @@
#!/bin/sh
-# Runs before every push: the three checks that are fast locally and that,
-# when they fail in CI, fail on every platform for a reason no reviewer can
-# fix — a type error, a lint error, a locale catalog that went stale. About
-# a minute here saves a 20-minute CI cycle and a red PR. The test suite is
-# deliberately NOT here: it takes 19 minutes, and CI shards it.
+# Runs before every push, in seconds: lint on the files this push changes, the locale check when a catalog changed, and
+# the size and vocabulary guards when a source they read changed (scripts/pre-push-check.mjs). The typecheck and the
+# suite stay in CI. A checkout without dependencies, as an agent's worktree often is, checks nothing and lets the push go.
#
-# Installed by `pnpm install` through scripts/install-git-hooks.mjs (sets
-# core.hooksPath). Skip once with `git push --no-verify`, or for a session
-# with OMB_SKIP_HOOKS=1.
-set -e
+# Installed by `pnpm install` through scripts/install-git-hooks.mjs (sets core.hooksPath). Skip once with
+# `git push --no-verify`, or for a session with OMB_SKIP_HOOKS=1.
if [ -n "$OMB_SKIP_HOOKS" ]; then
echo "pre-push: skipped (OMB_SKIP_HOOKS is set)"
exit 0
fi
-cd "$(git rev-parse --show-toplevel)"
-echo "pre-push: lint, typecheck, locale check (git push --no-verify to skip)"
-pnpm lint
-pnpm typecheck
-pnpm i18n:check
+cd "$(git rev-parse --show-toplevel)" || exit 0
+if [ ! -x node_modules/.bin/oxlint ] || [ ! -f scripts/pre-push-check.mjs ] || ! command -v node >/dev/null 2>&1; then
+ echo "pre-push: no dependencies in this checkout, so CI will check this push"
+ exit 0
+fi
+exec node scripts/pre-push-check.mjs
diff --git a/scripts/install-git-hooks.mjs b/scripts/install-git-hooks.mjs
index a0dc79dcf6..74cee9596f 100644
--- a/scripts/install-git-hooks.mjs
+++ b/scripts/install-git-hooks.mjs
@@ -20,6 +20,6 @@ try {
}
try {
execFileSync("git", ["config", "core.hooksPath", "scripts/git-hooks"], { cwd: root, stdio: "ignore" });
- console.log("git hooks: core.hooksPath -> scripts/git-hooks (pre-push runs lint, typecheck, i18n:check; OMB_SKIP_HOOKS=1 or --no-verify to skip)");
+ console.log("git hooks: core.hooksPath -> scripts/git-hooks (pre-push checks the changed files in seconds; OMB_SKIP_HOOKS=1 or --no-verify to skip)");
} catch {
}
diff --git a/scripts/pre-push-check.mjs b/scripts/pre-push-check.mjs
new file mode 100644
index 0000000000..176d0c16ba
--- /dev/null
+++ b/scripts/pre-push-check.mjs
@@ -0,0 +1,110 @@
+// What the pre-push hook checks: only the files the push changes, in seconds. CI still checks everything. This stops
+// the failures that are certain on every platform before they cost a CI run. Only a finding about this push stops it: no
+// origin/main, a dependency out of step, the time budget running out or main's own red all leave the push to CI.
+import { execFileSync, spawnSync } from "node:child_process";
+import { existsSync, mkdtempSync, readFileSync, rmSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join, resolve } from "node:path";
+import { fileURLToPath } from "node:url";
+
+const BUDGET_MS = 30_000;
+const CODE = /\.[cm]?[jt]sx?$/;
+// The tree the size ratchet counts, without tests, and the sources the vocabulary test reads.
+const RATCHETED = /^(?:server|shared|src|scripts|evals|electron|companion)\/.+\.(?:ts|tsx|mjs|cjs)$/;
+const WORDED = /^(?:src|server)\/.+\.(?:ts|tsx|json)$/;
+const isTest = (file) => /\.test\.[cm]?[jt]sx?$/.test(file) || file.includes("/testing/");
+
+/** The commits this push sends, from the hook's stdin: "<local ref> <local sha> <remote ref> <remote sha>" per line; a delete sends none. */
+export function pushedCommits(stdin) {
+ return stdin.split("\n").map((line) => line.trim().split(/\s+/))
+ .filter((fields) => fields.length === 4 && !/^0+$/.test(fields[1]))
+ .map((fields) => fields[1]);
+}
+
+/** The commands these files call for; none for a push that changes nothing they read. */
+export function checksFor(files) {
+ const checks = [];
+ const code = files.filter((file) => CODE.test(file));
+ if (code.length > 0) checks.push({ name: "lint", command: "node_modules/.bin/oxlint", args: ["--deny-warnings", ...code] });
+ if (files.some((file) => file.startsWith("src/locales/"))) checks.push({ name: "locale catalogs", command: "node", args: ["scripts/generate-locale.mjs", "--check"] });
+ const guards = [
+ ...(files.some((file) => RATCHETED.test(file) && !isTest(file)) ? ["scripts/testing/file-size-ratchet.test.ts"] : []),
+ ...(files.some((file) => WORDED.test(file) && !isTest(file)) ? ["src/locales/vocabulary.test.ts"] : []),
+ ];
+ if (guards.length > 0) checks.push({ name: "source guards", guards });
+ return checks;
+}
+
+const git = (...args) => execFileSync("git", args, { encoding: "utf8", stdio: ["ignore", "pipe", "ignore"] });
+
+/** Vitest's own verdict from its report, since a dependency out of step fails before any test runs. A guard reads the
+ * whole tree, so a failure that names none of the push's files is main's own, and that is CI's to report. */
+function runGuards(guards, files, timeout) {
+ const dir = mkdtempSync(join(tmpdir(), "omb-pre-push-"));
+ const report = join(dir, "report.json");
+ try {
+ const run = spawnSync("node_modules/.bin/vitest", ["run", ...guards, "--reporter=default", "--reporter=json", `--outputFile.json=${report}`], { encoding: "utf8", timeout, maxBuffer: 16 * 1024 * 1024 });
+ if (run.error) return { unknown: run.error.code === "ETIMEDOUT" ? `past ${BUDGET_MS / 1000} s` : run.error.code };
+ if (!existsSync(report)) return { unknown: "it did not start" };
+ if (JSON.parse(readFileSync(report, "utf8")).numFailedTests === 0) return {};
+ const output = `${run.stdout}${run.stderr}`;
+ // The vocabulary test names a catalog's key, not the catalog.
+ if (files.some((file) => output.includes(file) || file === "src/locales/en.json")) {
+ console.error(output);
+ return { failed: true };
+ }
+ return { unknown: "a failure that names no file of this push, so main may be red" };
+ } catch (error) {
+ return { unknown: error.message };
+ } finally {
+ rmSync(dir, { recursive: true, force: true });
+ }
+}
+
+function main() {
+ const started = Date.now();
+ const head = git("rev-parse", "HEAD").trim();
+ let files = [];
+ for (const sha of pushedCommits(readFileSync(0, "utf8"))) {
+ // The checks read the working tree, so they can only speak for what is checked out.
+ if (sha !== head) {
+ console.log(`pre-push: ${sha.slice(0, 9)} is not checked out here, so CI will check it`);
+ continue;
+ }
+ const base = git("merge-base", "origin/main", sha).trim();
+ files = git("diff", "--name-only", "--no-renames", "--diff-filter=d", "-z", base, sha).split("\0").filter(Boolean);
+ }
+ const present = files.filter((file) => existsSync(file));
+ for (const { name, command, args, guards } of checksFor(present)) {
+ const left = BUDGET_MS - (Date.now() - started);
+ if (left <= 0) {
+ console.log(`pre-push: out of time before ${name}, so CI will check it`);
+ break;
+ }
+ let bad;
+ if (guards) {
+ const verdict = runGuards(guards, present, left);
+ if (verdict.unknown) console.log(`pre-push: ${name} did not settle it (${verdict.unknown}), so CI will check them`);
+ bad = verdict.failed;
+ } else {
+ const run = spawnSync(command, args, { encoding: "utf8", timeout: left, maxBuffer: 16 * 1024 * 1024 });
+ if (run.error) console.log(`pre-push: ${name} did not finish (${run.error.code}), so CI will check it`);
+ bad = !run.error && run.status !== 0;
+ if (bad) console.error(`${run.stdout}${run.stderr}`);
+ }
+ if (bad) {
+ console.error(`pre-push: ${name} failed. Fix it, or push with OMB_SKIP_HOOKS=1 to let CI report it.`);
+ process.exitCode = 1;
+ return;
+ }
+ }
+ console.log(`pre-push: ${files.length} changed file(s) checked in ${((Date.now() - started) / 1000).toFixed(1)} s`);
+}
+
+if (process.argv[1] && resolve(process.argv[1]) === fileURLToPath(import.meta.url)) {
+ try {
+ main();
+ } catch (error) {
+ console.log(`pre-push: could not read this push (${String(error.message).split("\n")[0]}), so CI will check it`);
+ }
+}
diff --git a/scripts/pre-push-check.test.ts b/scripts/pre-push-check.test.ts
new file mode 100644
index 0000000000..a343d3a488
--- /dev/null
+++ b/scripts/pre-push-check.test.ts
@@ -0,0 +1,75 @@
+import { spawnSync, execFileSync } from "node:child_process";
+import { chmodSync, copyFileSync, mkdirSync, mkdtempSync, writeFileSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+import { fileURLToPath } from "node:url";
+import { afterAll, describe, expect, it } from "vitest";
+
+import { removeTempDir } from "../server/testing/cleanup.ts";
+import { checksFor, pushedCommits } from "./pre-push-check.mjs";
+
+const names = (files: string[]) => checksFor(files).map((check: { name: string }) => check.name);
+const guards = (files: string[]) => checksFor(files).find((check: { name: string }) => check.name === "source guards")?.guards ?? [];
+
+describe("what a push's changed files call for", () => {
+ it("lints only the changed code", () => {
+ const [lint] = checksFor(["server/a.ts", "docs/a.md", "src/b.tsx", "electron/c.mjs"]);
+ expect(lint.args).toEqual(["--deny-warnings", "server/a.ts", "src/b.tsx", "electron/c.mjs"]);
+ });
+
+ it("checks nothing for docs alone", () => {
+ expect(names(["README.md", "docs/ci.md"])).toEqual([]);
+ });
+
+ it("checks the catalogs only when one changed", () => {
+ expect(names(["src/locales/de.json"])).toContain("locale catalogs");
+ expect(names(["server/a.ts"])).not.toContain("locale catalogs");
+ });
+
+ it("runs a guard only when a source it reads changed", () => {
+ expect(guards(["server/index.ts"])).toEqual(["scripts/testing/file-size-ratchet.test.ts", "src/locales/vocabulary.test.ts"]);
+ expect(guards(["scripts/release-ci.mjs"])).toEqual(["scripts/testing/file-size-ratchet.test.ts"]);
+ expect(guards(["src/locales/en.json"])).toEqual(["src/locales/vocabulary.test.ts"]);
+ expect(guards(["server/a.test.ts", "server/testing/fake.ts"])).toEqual([]);
+ });
+
+ it("reads the pushed commits, and a deleted branch sends none", () => {
+ const sha = "a".repeat(40);
+ expect(pushedCommits(`refs/heads/x ${sha} refs/heads/x ${"0".repeat(40)}\n`)).toEqual([sha]);
+ expect(pushedCommits(`(delete) ${"0".repeat(40)} refs/heads/x ${sha}\n`)).toEqual([]);
+ expect(pushedCommits("")).toEqual([]);
+ });
+});
+
+describe("the hook in a checkout without dependencies", () => {
+ const dirs: string[] = [];
+ afterAll(async () => { for (const dir of dirs) await removeTempDir(dir); });
+
+ function checkout() {
+ const dir = mkdtempSync(join(tmpdir(), "omb-pre-push-hook-"));
+ dirs.push(dir);
+ const repo = (...args: string[]) => execFileSync("git", args, { cwd: dir, stdio: "ignore" });
+ repo("init", "-q");
+ repo("-c", "user.name=t", "-c", "[email protected]", "commit", "-q", "--allow-empty", "-m", "start");
+ mkdirSync(join(dir, "hooks"));
+ const hook = join(dir, "hooks", "pre-push");
+ copyFileSync(fileURLToPath(new URL("./git-hooks/pre-push", import.meta.url)), hook);
+ chmodSync(hook, 0o755);
+ return { dir, hook };
+ }
+
+ it.skipIf(process.platform === "win32")("lets the push go and says CI will check it", () => {
+ const { dir, hook } = checkout();
+ const run = spawnSync(hook, { cwd: dir, encoding: "utf8", input: "", timeout: 10_000 });
+ expect(run.status).toBe(0);
+ expect(run.stdout).toContain("no dependencies in this checkout");
+ });
+
+ it.skipIf(process.platform === "win32")("stays out of the way when skipped", () => {
+ const { dir, hook } = checkout();
+ writeFileSync(join(dir, "ignored"), "");
+ const run = spawnSync(hook, { cwd: dir, encoding: "utf8", input: "", timeout: 10_000, env: { ...process.env, OMB_SKIP_HOOKS: "1" } });
+ expect(run.status).toBe(0);
+ expect(run.stdout).toContain("skipped");
+ });
+});