|
| 1 | +#!/usr/bin/env node |
| 2 | +/** |
| 3 | + * pre-push-check.mjs — the AGENTS.md YAML/workflow lessons, executed before |
| 4 | + * every push instead of remembered after a red run. |
| 5 | + * |
| 6 | + * Each check names the lesson it enforces (the [C#] tags from the |
| 7 | + * Debugging Breakthroughs cost-ranked index): |
| 8 | + * |
| 9 | + * workflows-parse [C1] every .github/workflows file + the composite |
| 10 | + * action survives the real `yaml` parser and the |
| 11 | + * Actions schema walk (same authority as |
| 12 | + * test/ci/workflow-yaml-contract.test.js). |
| 13 | + * freeze-integrity [C2] the current freeze record verifies in |
| 14 | + * commit-anchored mode — editing a pinned file |
| 15 | + * without an honest re-pin fails here, not on CI. |
| 16 | + * pin-eol-cover [C3] every repo-root file pinned by the freeze record |
| 17 | + * (../-style paths) is covered by a `-text` |
| 18 | + * .gitattributes rule — the autocrlf drift class. |
| 19 | + * no-skip-ci [C*] no unpushed commit message carries a skip token |
| 20 | + * ("[skip ci]" et al.) — GitHub honors it from ANY |
| 21 | + * position in the message; the fix-commit that |
| 22 | + * contains it in prose skips itself (the vortex). |
| 23 | + * repin-reachable [C*] every postCommitRePins commit is an ancestor of |
| 24 | + * HEAD — a rebase rewrites the publication commit |
| 25 | + * and the ref would hash locally but be |
| 26 | + * COMMIT-MISSING on CI's fresh clone. |
| 27 | + * remote-fresh [C*] origin/main has not advanced (bot commits race |
| 28 | + * pushes here routinely) — if it has, fail with |
| 29 | + * the autostash-rebase remedy before push does. |
| 30 | + * |
| 31 | + * Exit codes: 0 all checks PASS (SKIP allowed for offline advisory checks) |
| 32 | + * 1 any FAIL · 2 usage error. |
| 33 | + * The verifier NEVER writes and NEVER pushes — it only gates. |
| 34 | + */ |
| 35 | + |
| 36 | +import { spawnSync } from "node:child_process"; |
| 37 | +import { readFileSync, readdirSync, existsSync } from "node:fs"; |
| 38 | +import { join, dirname, resolve } from "node:path"; |
| 39 | +import { fileURLToPath } from "node:url"; |
| 40 | +import { parse, YAMLParseError } from "yaml"; |
| 41 | + |
| 42 | +const args = process.argv.slice(2); |
| 43 | +const json = args.includes("--json"); |
| 44 | +const offline = args.includes("--offline"); |
| 45 | +const repo = resolve(process.env.PRE_PUSH_REPO || process.cwd()); |
| 46 | + |
| 47 | +const checks = []; |
| 48 | +function record(name, status, detail) { |
| 49 | + checks.push({ name, status, detail }); |
| 50 | + if (!json) console.log(`${status === "PASS" ? "✔" : status === "FAIL" ? "✗" : "·"} ${name.padEnd(17)} ${status.padEnd(5)} ${detail}`); |
| 51 | +} |
| 52 | +function git(repoCwd, gitArgs, opts = {}) { |
| 53 | + const r = spawnSync("git", ["-C", repoCwd, ...gitArgs], { encoding: "utf8", ...opts }); |
| 54 | + return { code: r.status, out: (r.stdout || "").trim(), err: (r.stderr || "").trim() }; |
| 55 | +} |
| 56 | + |
| 57 | +// ---- [C1] workflows-parse --------------------------------------------------- |
| 58 | +const workflowsDir = join(repo, ".github", "workflows"); |
| 59 | +const actionDir = join(repo, ".github", "actions", "coreguard-verify"); |
| 60 | +{ |
| 61 | + const files = existsSync(workflowsDir) |
| 62 | + ? readdirSync(workflowsDir).filter((f) => f.endsWith(".yml") || f.endsWith(".yaml")).map((f) => join(workflowsDir, f)) |
| 63 | + : []; |
| 64 | + if (existsSync(actionDir)) { |
| 65 | + for (const name of ["action.yml", "action.yaml"]) { |
| 66 | + const p = join(actionDir, name); |
| 67 | + if (existsSync(p)) files.push(p); |
| 68 | + } |
| 69 | + } |
| 70 | + const bad = []; |
| 71 | + for (const f of files) { |
| 72 | + try { |
| 73 | + parse(readFileSync(f, "utf8")); |
| 74 | + } catch (e) { |
| 75 | + bad.push(`${f.replace(repo + "\\", "").replace(repo + "/", "")}: ${e instanceof YAMLParseError ? e.message.split("\n")[0] : e.message}`); |
| 76 | + } |
| 77 | + } |
| 78 | + record("workflows-parse", bad.length ? "FAIL" : "PASS", |
| 79 | + bad.length ? `${bad.length} unparseable — ${bad[0]}${bad.length > 1 ? ` (+${bad.length - 1} more)` : ""}` : `${files.length} file(s) parse clean [C1]`); |
| 80 | +} |
| 81 | + |
| 82 | +// ---- [C2] freeze-integrity --------------------------------------------------- |
| 83 | +const RECORD = join(repo, "coreguard-assurance-v4.2.2-remediation", "release", "freeze", "freeze-record-4.2.6.json"); |
| 84 | +const VERIFIER = join(repo, "coreguard-assurance-v4.2.2-remediation", "verification", "validate-freeze.mjs"); |
| 85 | +let recordJson = null; |
| 86 | +try { recordJson = JSON.parse(readFileSync(RECORD, "utf8")); } catch { /* record-shape checks skip */ } |
| 87 | +if (!existsSync(RECORD) || !existsSync(VERIFIER)) { |
| 88 | + record("freeze-integrity", "SKIP", "freeze record or verifier not found in this repo layout"); |
| 89 | +} else { |
| 90 | + const v = spawnSync(process.execPath, [VERIFIER, RECORD], { encoding: "utf8", cwd: repo }); |
| 91 | + const passLine = (v.stdout || "").split("\n").find((l) => l.startsWith("validate-freeze:")); |
| 92 | + if (v.status === 0) { |
| 93 | + record("freeze-integrity", "PASS", (passLine || "PASS").trim()); |
| 94 | + } else { |
| 95 | + record("freeze-integrity", "FAIL", `exit ${v.status} — ${(passLine || (v.stderr || "").split("\n")[0] || "?").trim()} (edit a pinned file? re-pin per the integrity rule first)`); |
| 96 | + } |
| 97 | +} |
| 98 | + |
| 99 | +// ---- [C3] pin-eol-cover ------------------------------------------------------- |
| 100 | +if (!recordJson) { |
| 101 | + record("pin-eol-cover", "SKIP", "no freeze record parsed"); |
| 102 | +} else { |
| 103 | + const gaPath = join(repo, ".gitattributes"); |
| 104 | + const rules = existsSync(gaPath) |
| 105 | + ? readFileSync(gaPath, "utf8").split("\n") |
| 106 | + .map((l) => l.trim()).filter((l) => l && !l.startsWith("#")) |
| 107 | + .filter((l) => l.split(/\s+/).slice(1).includes("-text")) |
| 108 | + .map((l) => l.split(/\s+/)[0]) |
| 109 | + : []; |
| 110 | + function covered(repoRel) { |
| 111 | + return rules.some((rule) => { |
| 112 | + if (rule === repoRel) return true; |
| 113 | + if (rule.endsWith("/**")) return repoRel.startsWith(rule.slice(0, -3)); |
| 114 | + if (rule.includes("*")) { |
| 115 | + const re = new RegExp("^" + rule.split("*").map((s) => s.replace(/[.+^${}()|[\]\\]/g, "\\$&")).join("[^/]*") + "$"); |
| 116 | + return re.test(repoRel); |
| 117 | + } |
| 118 | + return false; |
| 119 | + }); |
| 120 | + } |
| 121 | + const rootPins = new Set(); |
| 122 | + for (const e of recordJson.sha256?.quarantineFiles ?? []) rootPins.add(e.file.replace(/^(?:\.\.\/)+/, "")); |
| 123 | + for (const e of recordJson.postCommitRePins ?? []) if (e.file.startsWith("..")) rootPins.add(e.file.replace(/^(?:\.\.\/)+/, "")); |
| 124 | + const uncovered = [...rootPins].filter((p) => !covered(p)); |
| 125 | + record("pin-eol-cover", uncovered.length ? "FAIL" : "PASS", |
| 126 | + uncovered.length ? `pinned file(s) without a -text rule: ${uncovered.join(", ")} — add to .gitattributes BEFORE trusting any pin [C3]` |
| 127 | + : `${rootPins.size} repo-root pin(s) all -text-covered [C3]`); |
| 128 | +} |
| 129 | + |
| 130 | +// ---- [C*] no-skip-ci in unpushed commit messages ------------------------------- |
| 131 | +{ |
| 132 | + const hasOrigin = git(repo, ["rev-parse", "--verify", "origin/main"]); |
| 133 | + if (hasOrigin.code !== 0) { |
| 134 | + record("no-skip-ci", "SKIP", "no origin/main yet (first push)"); |
| 135 | + } else { |
| 136 | + const log = git(repo, ["log", "origin/main..HEAD", "--format=%B%x00"], { maxBuffer: 4 * 1024 * 1024 }); |
| 137 | + const msgs = log.out.split("\0").map((m) => m.trim()).filter(Boolean); |
| 138 | + const TOKEN = /\[(?:skip\s+ci|ci\s+skip|skip\s+actions|actions\s+skip)\]/i; |
| 139 | + const offenders = msgs.filter((m) => TOKEN.test(m)).map((m) => m.split("\n")[0].slice(0, 60)); |
| 140 | + record("no-skip-ci", offenders.length ? "FAIL" : "PASS", |
| 141 | + offenders.length |
| 142 | + ? `skip token in an unpushed message (honored from ANY position): "${offenders[0]}" — rewrite the message (rebase -i / drop the token)` |
| 143 | + : `${msgs.length} unpushed commit(s), none carries a skip token`); |
| 144 | + } |
| 145 | +} |
| 146 | + |
| 147 | +// ---- [C*] repin-reachable ------------------------------------------------------- |
| 148 | +if (!recordJson || !Array.isArray(recordJson.postCommitRePins)) { |
| 149 | + record("repin-reachable", "SKIP", "no freeze record parsed"); |
| 150 | +} else { |
| 151 | + const bad = []; |
| 152 | + for (const e of recordJson.postCommitRePins) { |
| 153 | + const anc = git(repo, ["merge-base", "--is-ancestor", String(e.commit), "HEAD"]); |
| 154 | + if (anc.code !== 0) bad.push(`${e.file} → ${String(e.commit).slice(0, 12)}`); |
| 155 | + } |
| 156 | + record("repin-reachable", bad.length ? "FAIL" : "PASS", |
| 157 | + bad.length |
| 158 | + ? `re-pin commit(s) NOT ancestors of HEAD (rewritten by a rebase?): ${bad[0]} — re-point the ref at the commit actually on main` |
| 159 | + : `${recordJson.postCommitRePins.length} re-pin ref(s) reachable from HEAD`); |
| 160 | +} |
| 161 | + |
| 162 | +// ---- [C*] remote-fresh ----------------------------------------------------------- |
| 163 | +if (offline) { |
| 164 | + record("remote-fresh", "SKIP", "--offline (skipping the advisory fetch)"); |
| 165 | +} else { |
| 166 | + const fetch = git(repo, ["fetch", "origin", "main"]); |
| 167 | + const hasOrigin = git(repo, ["rev-parse", "--verify", "origin/main"]); |
| 168 | + if (fetch.code !== 0 && hasOrigin.code !== 0) { |
| 169 | + record("remote-fresh", "SKIP", `no origin/main reachable (${(fetch.err || "fetch failed").split("\n")[0]})`); |
| 170 | + } else { |
| 171 | + const behind = git(repo, ["rev-list", "--count", "HEAD..origin/main"]); |
| 172 | + const n = Number(behind.out || "0"); |
| 173 | + record("remote-fresh", n > 0 ? "FAIL" : "PASS", |
| 174 | + n > 0 |
| 175 | + ? `origin/main advanced by ${n} commit(s) (bot race) — git pull --rebase --autostash origin main BEFORE pushing` |
| 176 | + : "origin/main not ahead of HEAD"); |
| 177 | + } |
| 178 | +} |
| 179 | + |
| 180 | +// ---- summary --------------------------------------------------------------------- |
| 181 | +const fails = checks.filter((c) => c.status === "FAIL").slice(0, 3); |
| 182 | +if (json) console.log(JSON.stringify({ ok: fails.length === 0, repo, checks }, null, 2)); |
| 183 | +else { |
| 184 | + console.log("─".repeat(72)); |
| 185 | + console.log(fails.length |
| 186 | + ? `pre-push-check: FAIL (${checks.filter((c) => c.status === "FAIL").length} of ${checks.length} checks) — ${fails[0].detail}` |
| 187 | + : `pre-push-check: PASS (${checks.filter((c) => c.status === "PASS").length} PASS · ${checks.filter((c) => c.status === "SKIP").length} SKIP) — safe to push`); |
| 188 | +} |
| 189 | +process.exit(checks.some((c) => c.status === "FAIL") ? 1 : 0); |
0 commit comments