Skip to content

Commit d36978c

Browse files
feat(ci): mechanical pre-push checklist built from the AGENTS.md YAML/workflow lessons
npm run prepush (scripts/pre-push-check.mjs) executes the lessons before every push instead of remembering them after a red run. Six fail-closed checks, each naming the lesson tag it enforces: workflows-parse [C1] real-YAML parse of all workflows + the composite action (same authority as the CI contract test) freeze-integrity [C2] commit-anchored freeze verification pin-eol-cover [C3] every repo-root pin covered by a -text rule no-skip-ci skip tokens honored from ANY message position (the fix-commit that contains it in prose skips itself - the documented vortex) repin-reachable re-pin commits must be ancestors of HEAD (a rebase rewrite hashes locally, COMMIT-MISSING on CI's fresh clone) remote-fresh origin/main not ahead; bot races get the exact autostash-rebase remedy named in the failure --json for machines, human summary with exit 0/1; --offline skips the advisory fetch. Proven by 5 contract tests: a happy path on the real repo plus sandboxed fail-closed proofs (unparseable YAML named by file, a mid-message skip token, an orphaned re-pin ref named while the reachable one stays silent, a raced remote). The checklist caught a live bot race during its own first run and gated the push until the rebase remedy was applied - the loop closes on itself. Generated with Codebuff 🤖 Co-Authored-By: Codebuff <noreply@codebuff.com>
1 parent e04d75e commit d36978c

4 files changed

Lines changed: 373 additions & 1 deletion

File tree

‎AGENTS.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -52,7 +52,7 @@ title to jump.
5252
| C10 | Resolve pin paths before declaring a freeze violation | near-miss: almost triggered an unnecessary re-pin cycle |
5353
| C11 | NegativeSuite premise path | contained: the suite fails correctly — just run it from the platform dir |
5454

55-
- [C1] **Multi-line plain scalar with `": "` kills the whole workflow (zero jobs)**: a `run:` value written as a plain (non-block) multi-line YAML scalar containing a JS literal like `console.error('health check failed: ...')` — the `": "` inside a plain scalar is unparseable → GitHub marks the run `failure` with **zero jobs built**. That zero-jobs conclusion IS the signature of an unparseable workflow file (not a failing step). Fix: any multi-line `run:` must be a real block scalar (`run: |` on its own line). Trap within the trap: a string-matching "validator" whose `||` fallback jumped to a fake parser reported PASS — only a real YAML parser or GitHub itself building the job proves the file parses (cost a push + a red run). Now enforced mechanically: `test/ci/workflow-yaml-contract.test.js` parses every `.github/workflows` file and the composite action with the real `yaml` parser (dev dep) plus an Actions schema walk — an unparseable or schema-deviant file fails the push locally with file+line naming, before GitHub ever sees it.
55+
- [C1] **Multi-line plain scalar with `": "` kills the whole workflow (zero jobs)**: a `run:` value written as a plain (non-block) multi-line YAML scalar containing a JS literal like `console.error('health check failed: ...')` — the `": "` inside a plain scalar is unparseable → GitHub marks the run `failure` with **zero jobs built**. That zero-jobs conclusion IS the signature of an unparseable workflow file (not a failing step). Fix: any multi-line `run:` must be a real block scalar (`run: |` on its own line). Trap within the trap: a string-matching "validator" whose `||` fallback jumped to a fake parser reported PASS — only a real YAML parser or GitHub itself building the job proves the file parses (cost a push + a red run). Now enforced mechanically: `test/ci/workflow-yaml-contract.test.js` parses every `.github/workflows` file and the composite action with the real `yaml` parser (dev dep) plus an Actions schema walk — an unparseable or schema-deviant file fails the push locally with file+line naming, before GitHub ever sees it. Runs inside `npm run prepush` too (scripts/pre-push-check.mjs), the mechanical pre-push checklist built from the YAML/workflow lessons: workflows-parse [C1] · freeze-integrity [C2] · pin-eol-cover [C3] · no-skip-ci (the skip-token vortex) · repin-reachable (the rebase rewrite trap) · remote-fresh (the bot race, with the autostash remedy named).
5656
- [C2] **Commit-anchored verification (4.2.6+)**: `validate-freeze.mjs` hashes `git show <gitCommit>:<path>` blobs, not disk bytes. Disk mode (`--disk`) is triage-only, prints "not evidence". Records without `gitCommit` fail COMMIT-UNANCHORED (historical included — correct). Editing a file whose bytes exist only in a future commit requires a **two-phase re-anchor**: commit phase 1, then point `gitCommit`/`postCommitRePins` at that hash in phase 2. Release entries are platform-dir relative; quarantine entries repo-root relative; repo-root files outside the platform dir use `../` prefixes (stripped by `treePath`/`repoRelPath` — the honesty test must mirror this or bare-name pins hash the wrong file).
5757
- [C3] **`git show HEAD:file` ≠ disk ≠ fresh-clone disk**: a pinned file outside every `-text` rule in `.gitattributes` is silently CRLF-rewritten on ANY fresh clone when `core.autocrlf=true` is set (system default on Windows) — the main working tree can hold LF bytes while a reviewer's pristine clone drifts and fails `--disk`. Always prove "clean-clone" claims from an actual fresh clone/`git -c core.autocrlf=false clone`, not from the dev disk. Any file newly pinned in a freeze record (including `../docs/…` — root-level pins outside the three `-text` trees) must be added to `.gitattributes` **and** the RC manifest must be rebuilt from a pristine `autocrlf=false` checkout (`scripts/build-rc-manifest.mjs` reads the disk, so generating on an autocrlf machine pins CRLF hashes that blobs don't match).
5858
- [C4] **Bilingual dashboard i18n architecture (the pattern that works)**: three defects killed the first attempt — (1) swapping only the first text node left Arabic tails around inline children (`.ltr`, badges); (2) the resolver `L()` was scoped inside an IIFE that ran after the views' initial render → `L is not defined` + dead toggle; (3) attr swaps targeted markup markers that didn't exist. The working design: **hoisted global `L()` prelude** at script top reading live language from `window.cgLang` at call time; **full `innerHTML` swap** per `[data-i18n]` element (text + inline children together, no tails); **views re-render on a `cg41:lang` CustomEvent**; dynamic strings stored as `{ar,en}` pairs resolved through `L()`; attrs applied by unique selectors, not markers. Dictionary generated by structural pairing (637/637 nodes) against the EN sister — never hand-maintained.

‎package.json‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@
1414
"benchmark:dde": "node scripts/benchmark-dde.mjs",
1515
"benchmark:dde-http": "node scripts/benchmark-dde-http.mjs",
1616
"publish:check": "node scripts/publish-check.mjs",
17+
"prepush": "node scripts/pre-push-check.mjs",
1718
"release:dry": "node scripts/release-please.mjs --dry-run",
1819
"mutation": "node scripts/mutation-lab.mjs",
1920
"corpus": "node benchmarks/generate-corpus.js",

‎scripts/pre-push-check.mjs‎

Lines changed: 189 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,189 @@
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

Comments
 (0)