Skip to content

armgit / 67.js

Public Imported from GitHub
0

3D engine that AI agents drive

Run the fast preflight gates in a pre-push hook

Nguyen Xuan An7c671f6e8b91
diff --git a/.githooks/pre-push b/.githooks/pre-push
new file mode 100755
index 00000000..ce733dc1
--- /dev/null
+++ b/.githooks/pre-push
@@ -0,0 +1,4 @@
+#!/bin/sh
+# Runs the fast preflight gates before a push. Installed by `npm install` (scripts/install-git-hooks.mjs).
+# Skip once with SKIP_PREFLIGHT=1 git push, or git push --no-verify.
+exec node scripts/pre-push.mjs "$@"
diff --git a/AGENTS.md b/AGENTS.md
index fbcdbd49..9e60f13b 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -30,6 +30,8 @@ tool schemas, size, tool cost, the build, the unit tests with coverage and the c
writes each log to `artifacts/preflight/`, prints only the tail of a failing log and ends with one line per check and its fix.
`--skip-tests` skips the slow test pass while you iterate, and `--json` adds a machine-readable summary.
Run the full preflight once before you push. A green preflight means the `test` check should pass.
+`npm ci` installs a pre-push hook that runs `npm run preflight -- --skip-tests` and stops a push that would fail those gates.
+`SKIP_PREFLIGHT=1 git push` skips it once; use that only for a push you know the gates do not cover.
For one test file: `node --test tests/<area>.test.js`.
diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md
index 6e8e5876..ddf94f0e 100644
--- a/CONTRIBUTING.md
+++ b/CONTRIBUTING.md
@@ -27,6 +27,8 @@ The tests are in `tests/` and the guides are in `docs/`.
Run `npm run preflight` before you open a pull request. It runs every check below that applies to the files you changed, plus the size, tool cost and coverage gates, keeps going after a failure and ends with one line per check and how to fix it. Logs go to `artifacts/preflight/`. `--skip-tests` skips the slow test pass while you iterate.
+`npm ci` points git at `.githooks/`, whose pre-push hook runs `npm run preflight -- --skip-tests` and stops the push when a gate fails. Pushing only tags or branch deletions skips it. `SKIP_PREFLIGHT=1 git push` skips it once. The unit tests stay out of the hook because they take minutes; run the full preflight before you open the pull request.
+
The checks it runs, if you want one alone:
1. Run `npm test`. All Node tests must pass.
diff --git a/package.json b/package.json
index 2212d836..715e8c57 100644
--- a/package.json
+++ b/package.json
@@ -120,6 +120,7 @@
"./package.json": "./package.json"
},
"scripts": {
+ "prepare": "node scripts/install-git-hooks.mjs",
"dev": "vite --host 127.0.0.1",
"build": "node scripts/prepare-release.mjs && vite build",
"build:lib": "vite build --config vite.lib.config.js",
diff --git a/scripts/install-git-hooks.mjs b/scripts/install-git-hooks.mjs
new file mode 100644
index 00000000..6b3bc1c0
--- /dev/null
+++ b/scripts/install-git-hooks.mjs
@@ -0,0 +1,45 @@
+// Points git at .githooks/ so the pre-push preflight runs in every clone and worktree. Runs from the npm `prepare`
+// script. Does nothing on CI, outside a git checkout, or when the clone already uses another hooks folder on purpose.
+import { spawnSync } from 'node:child_process';
+import { existsSync } from 'node:fs';
+import { join, resolve } from 'node:path';
+import { fileURLToPath, pathToFileURL } from 'node:url';
+
+const root = fileURLToPath(new URL('..', import.meta.url));
+const hooksFolder = '.githooks';
+
+// Decides what to do with the current core.hooksPath. Pure, so tests can call it without git.
+export function planHooksInstall({ isCi, isGitCheckout, currentHooksPath }) {
+ if (isCi) return { install: false, reason: 'CI' };
+ if (!isGitCheckout) return { install: false, reason: 'not a git checkout' };
+ if (currentHooksPath === hooksFolder) return { install: false, reason: 'already installed' };
+ if (currentHooksPath) return { install: false, reason: `core.hooksPath is already ${currentHooksPath}` };
+ return { install: true, reason: null };
+}
+
+function git(args) {
+ return spawnSync('git', args, { cwd: root, encoding: 'utf8' });
+}
+
+function main() {
+ const currentHooksPath = git(['config', '--get', 'core.hooksPath']).stdout?.trim() || null;
+ const plan = planHooksInstall({
+ isCi: Boolean(process.env.CI),
+ isGitCheckout: existsSync(join(root, '.git')),
+ currentHooksPath,
+ });
+ if (!plan.install) {
+ if (plan.reason.startsWith('core.hooksPath')) console.log(`Git hooks not installed: ${plan.reason}.`);
+ return;
+ }
+ const result = git(['config', 'core.hooksPath', hooksFolder]);
+ if (result.status === 0) {
+ console.log('Git hooks installed: the pre-push hook runs the fast preflight checks.');
+ } else {
+ console.warn(`Could not install git hooks: ${result.stderr.trim()}`);
+ }
+}
+
+if (import.meta.url === pathToFileURL(resolve(process.argv[1] ?? '')).href) {
+ main();
+}
diff --git a/scripts/pre-push.mjs b/scripts/pre-push.mjs
new file mode 100644
index 00000000..0945ab82
--- /dev/null
+++ b/scripts/pre-push.mjs
@@ -0,0 +1,47 @@
+// Git pre-push hook body. Runs `npm run preflight -- --skip-tests` so a branch that would fail the fast gates of the
+// `Test` workflow (protected files, change note, links, tool schemas, size, tool cost) stops on this machine instead of
+// on CI. The unit tests stay on CI and in the full `npm run preflight`, because they take minutes.
+// Git passes one line per pushed ref on stdin: "<local ref> <local sha> <remote ref> <remote sha>".
+import { spawnSync } from 'node:child_process';
+import { readFileSync } from 'node:fs';
+import { fileURLToPath, pathToFileURL } from 'node:url';
+import { resolve } from 'node:path';
+
+const root = fileURLToPath(new URL('..', import.meta.url));
+const deletedSha = /^0+$/;
+
+// Decides whether a push needs the preflight. Pure, so tests can call it without git.
+export function shouldRunPreflight(pushedRefsText, environment = {}) {
+ if (environment.SKIP_PREFLIGHT === '1') {
+ return { run: false, reason: 'SKIP_PREFLIGHT=1' };
+ }
+ const pushedBranches = pushedRefsText
+ .split(/\r?\n/)
+ .map(line => line.trim().split(/\s+/))
+ .filter(fields => fields.length === 4)
+ // The remote ref decides: `git push origin HEAD` reports the local ref as "HEAD", not refs/heads/<name>.
+ .filter(([, localSha, remoteRef]) => remoteRef.startsWith('refs/heads/') && !deletedSha.test(localSha));
+ if (pushedBranches.length === 0) {
+ return { run: false, reason: 'no branch commits pushed (tags or deletions only)' };
+ }
+ return { run: true, reason: null };
+}
+
+function main() {
+ const pushedRefsText = readFileSync(0, 'utf8');
+ const decision = shouldRunPreflight(pushedRefsText, process.env);
+ if (!decision.run) {
+ console.log(`pre-push: preflight skipped, ${decision.reason}.`);
+ return 0;
+ }
+ console.log('pre-push: running npm run preflight -- --skip-tests. Skip once with SKIP_PREFLIGHT=1 git push.');
+ const result = spawnSync('node', ['scripts/preflight.mjs', '--skip-tests'], { cwd: root, stdio: 'inherit' });
+ if (result.status !== 0) {
+ console.error('pre-push: push stopped. Fix the checks above, or push anyway with SKIP_PREFLIGHT=1 git push.');
+ }
+ return result.status ?? 1;
+}
+
+if (import.meta.url === pathToFileURL(resolve(process.argv[1] ?? '')).href) {
+ process.exit(main());
+}
diff --git a/tests/git-hooks.test.js b/tests/git-hooks.test.js
new file mode 100644
index 00000000..cc71ee6f
--- /dev/null
+++ b/tests/git-hooks.test.js
@@ -0,0 +1,39 @@
+import { test } from 'node:test';
+import assert from 'node:assert/strict';
+import { shouldRunPreflight } from '../scripts/pre-push.mjs';
+import { planHooksInstall } from '../scripts/install-git-hooks.mjs';
+
+const someSha = 'a'.repeat(40);
+const deletedSha = '0'.repeat(40);
+
+test('pushing a branch runs the preflight', () => {
+ const pushed = `refs/heads/feat/1-x ${someSha} refs/heads/feat/1-x ${deletedSha}\n`;
+ assert.deepEqual(shouldRunPreflight(pushed, {}), { run: true, reason: null });
+});
+
+test('pushing HEAD to a branch runs the preflight', () => {
+ const pushed = `HEAD ${someSha} refs/heads/feat/1-x ${someSha}\n`;
+ assert.equal(shouldRunPreflight(pushed, {}).run, true);
+});
+
+test('deleting a branch or pushing only a tag skips the preflight', () => {
+ const deletion = `(delete) ${deletedSha} refs/heads/old ${someSha}\n`;
+ assert.equal(shouldRunPreflight(deletion, {}).run, false);
+ const tag = `refs/tags/v1.0.0 ${someSha} refs/tags/v1.0.0 ${deletedSha}\n`;
+ assert.match(shouldRunPreflight(tag, {}).reason, /tags or deletions/);
+ assert.equal(shouldRunPreflight('', {}).run, false);
+});
+
+test('SKIP_PREFLIGHT=1 skips the preflight', () => {
+ const pushed = `refs/heads/main ${someSha} refs/heads/main ${someSha}\r\n`;
+ assert.deepEqual(shouldRunPreflight(pushed, { SKIP_PREFLIGHT: '1' }), { run: false, reason: 'SKIP_PREFLIGHT=1' });
+});
+
+test('hooks install only in a local git checkout without another hooks folder', () => {
+ const local = { isCi: false, isGitCheckout: true, currentHooksPath: null };
+ assert.equal(planHooksInstall(local).install, true);
+ assert.equal(planHooksInstall({ ...local, isCi: true }).reason, 'CI');
+ assert.equal(planHooksInstall({ ...local, isGitCheckout: false }).reason, 'not a git checkout');
+ assert.equal(planHooksInstall({ ...local, currentHooksPath: '.githooks' }).reason, 'already installed');
+ assert.match(planHooksInstall({ ...local, currentHooksPath: '.husky' }).reason, /already \.husky/);
+});