Files
OmniRoute/scripts/check/newCodeMode.mjs
diegosouzapw 56a327c727 fix(ci): judge an omni-queue candidate against its base, like a pull request
A push to omni-queue/** has no github.event.pull_request, so the gates that
are base-relative (or advisory) on a pull request ran a candidate in their
absolute / strict mode. A base that drifted mid-cycle would red every
candidate and the queue would blame innocent pull requests. Measured on the
release tip: the strict i18n drift check exits 1 (33 sources, 66 mirrors).

On a candidate these now compare with needs.changes.outputs.candidateBase:

- ci.yml lint: boundary ratchet (--base-ref).
- quality.yml fast-gates: file-size, complexity-ratchets, dead-code, boundary
  and the TS7 diagnostics ratchet (which was skipped without a base).
- ci.yml docs-sync-strict: the i18n docs drift takes the pull-request path
  (base checkout of the candidate base + advisory comparison); the strict
  step no longer runs on a candidate.

Pushes to main, merge_group and workflow_dispatch evaluate to the same
values as before; pull requests keep github.event.pull_request.base.sha.

newCodeMode.resolveMergeBase: on a merge-commit HEAD it compares with HEAD^1
(the live base tip of refs/pull/N/merge). A batch candidate is the base plus
one merge commit per pull request, so that rule judged only the last pull
request of the batch. The two new-code gates now pass the pushed ref, and a
refs/heads/omni-queue/** ref compares with the given base. Every other ref
keeps the first-parent rule. GITHUB_REF joins the runner-owned variables of
check-env-doc-sync (the gates read it; it is not OmniRoute configuration).

Existing assertions changed on purpose (same strictness, new expression):
- tests/unit/build/check-boundary-ratchet.test.ts: the two exact matches of
  the PR_BASE_SHA binding (ci.yml lint, quality.yml fast-gates) now expect
  "github.event.pull_request.base.sha || needs.changes.outputs.candidateBase".
- tests/unit/quality-rail-gate-membership.test.ts: the PR_BASE_SHA regex of
  the TS7 ratchet expects the same expression.
2026-11-14 12:45:19 -03:00

209 lines
7.7 KiB
JavaScript

// scripts/check/newCodeMode.mjs
// "New code" mode for the ratchet gates (Sonar "Clean as You Code", applied 2026-08-30).
//
// A global ratchet ("total violations ≤ baseline") makes an innocent PR red whenever the
// base drifted — and it lets a PR that adds 10 violations pass as long as someone else
// removed 11. In new-code mode (`--base-ref <sha>`: PR events, and omni-queue candidates
// against their base) a gate compares the PR's HEAD against the merge-base **restricted to
// the files the PR touched**:
//
// blocking → the PR added violations / dead symbols in files it changed
// advisory → the global total vs. the frozen baseline (printed, never exit 1);
// the release reconciliation re-measures and re-freezes it
//
// Shared by check-complexity-ratchets.mjs and check-dead-code.mjs. Everything git-related
// is here; the pure comparison helpers are unit-tested (tests/unit/build/new-code-mode.test.ts).
import { execFileSync } from "node:child_process";
import fs from "node:fs";
import os from "node:os";
import path from "node:path";
import { fileURLToPath } from "node:url";
export const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "..", "..");
/** CLI arg helper shared by the gates: `--base-ref <sha>` → sha | null. */
export function baseRefArg(argv = process.argv) {
const i = argv.indexOf("--base-ref");
return i >= 0 && argv[i + 1] ? argv[i + 1] : null;
}
function git(args, opts = {}) {
return execFileSync("git", args, {
cwd: ROOT,
encoding: "utf8",
stdio: ["ignore", "pipe", "pipe"],
maxBuffer: 64 * 1024 * 1024,
...opts,
}).trim();
}
const QUEUE_CANDIDATE_REF = /^refs\/heads\/omni-queue\//;
/**
* Merge-base between the PR base ref and HEAD (falls back to the ref itself).
*
* GitHub checks PRs out at `refs/pull/N/merge`: a merge commit whose FIRST parent
* is the live base tip at job time. `github.event.pull_request.base.sha` stays at
* the commit the PR was OPENED against, so once the base moves,
* `merge-base(ref, HEAD)` silently diffs the base's own newer commits onto the PR
* (#15346/#15322 — a #12740 base change blamed on unrelated PRs). When HEAD is a
* merge commit and `baseRef` is an ancestor of HEAD^1, compare against HEAD^1:
* that diff is exactly the PR's new code, matching GitHub's "Files changed" view.
*
* Not on an omni-queue candidate (`ref` = the pushed ref, `refs/heads/omni-queue/**`): it is
* the base plus one merge commit per batched PR, so HEAD^1 is the candidate without its LAST
* pull request, and `baseRef` (the Omni-Queue-Base the batch was composed on) is never stale.
* The first-parent rule would judge only the last PR of the batch.
*/
export function resolveMergeBase(baseRef, { cwd = ROOT, ref } = {}) {
try {
const parents = git(["rev-list", "--parents", "-n", "1", "HEAD"], { cwd }).split(/\s+/);
const firstParent = parents[1];
if (parents.length > 2 && firstParent && !QUEUE_CANDIDATE_REF.test(ref ?? "")) {
// Throws (exit 1) when baseRef is NOT an ancestor of the live base tip —
// i.e. a local diverged branch, where merge-base semantics still apply.
git(["merge-base", "--is-ancestor", baseRef, firstParent], { cwd });
return firstParent;
}
} catch {
/* not a merge commit, or baseRef not an ancestor — fall through */
}
try {
return git(["merge-base", baseRef, "HEAD"], { cwd });
} catch {
return git(["rev-parse", baseRef], { cwd });
}
}
/**
* Files added/copied/modified/renamed between `mergeBase` and HEAD, filtered to the gate's
* scope. Deleted files are irrelevant (nothing to measure on HEAD).
*/
export function listChangedFiles(mergeBase, { dirs, exts, excludePrefixes = [] }) {
const out = git(["diff", "--name-only", "--diff-filter=ACMR", `${mergeBase}...HEAD`]);
return filterScope(out.split("\n"), { dirs, exts, excludePrefixes });
}
/** Pure: keep paths under one of `dirs` with one of `exts`. */
export function filterScope(paths, { dirs, exts, excludePrefixes = [] }) {
return paths
.map((p) => p.trim())
.filter(Boolean)
.filter((p) => dirs.some((d) => p === d || p.startsWith(`${d}/`)))
.filter((p) => exts.some((e) => p.endsWith(e)))
.filter((p) => !excludePrefixes.some((prefix) => p.startsWith(prefix)))
.sort();
}
/**
* Materialize `sha` in a throwaway worktree with node_modules linked from ROOT, run `fn(dir)`,
* always tear it down. Never touches the caller's tree or index (no stash, no checkout).
*/
export function withBaseWorktree(sha, fn) {
const dir = fs.mkdtempSync(path.join(os.tmpdir(), "omniroute-newcode-base-"));
fs.rmdirSync(dir); // git worktree add wants a non-existent path
git(["worktree", "add", "--detach", "--quiet", dir, sha]);
try {
const nm = path.join(ROOT, "node_modules");
if (fs.existsSync(nm)) fs.symlinkSync(nm, path.join(dir, "node_modules"), "dir");
return fn(dir);
} finally {
try {
git(["worktree", "remove", "--force", dir]);
} catch {
fs.rmSync(dir, { recursive: true, force: true, maxRetries: 5, retryDelay: 100 });
try {
git(["worktree", "prune"]);
} catch {
/* best effort */
}
}
}
}
/**
* Pure: per-file count of ESLint messages whose ruleId is in `rules`.
* `filePath` is made relative to `cwd` so HEAD and base reports share keys.
*/
export function perFileRuleCounts(report, rules, cwd) {
let realCwd = cwd;
try {
realCwd = fs.realpathSync(cwd);
} catch {
/* fallback to cwd */
}
const counts = new Map();
for (const entry of report || []) {
let filePath = entry.filePath;
if (path.isAbsolute(filePath)) {
try {
filePath = fs.realpathSync(filePath);
} catch {
/* fallback */
}
}
const rel = path.isAbsolute(filePath)
? path.relative(realCwd, filePath).split(path.sep).join("/")
: filePath;
let n = 0;
for (const m of entry.messages || []) if (rules.has(m.ruleId)) n++;
counts.set(rel, (counts.get(rel) || 0) + n);
}
return counts;
}
/**
* Pure: which changed files gained violations. A file absent from the base map is new
* (base = 0). Returns the per-file regressions and the net delta over the changed set.
*/
export function diffNewCode(headCounts, baseCounts, changedFiles) {
const regressions = [];
let head = 0;
let base = 0;
for (const file of changedFiles) {
const h = headCounts.get(file) || 0;
const b = baseCounts.get(file) || 0;
head += h;
base += b;
if (h > b) regressions.push({ file, base: b, head: h });
}
return { regressions, head, base, delta: head - base };
}
/** Pure: `file:symbol` keys of every dead export/type in a knip JSON report. */
export function deadSymbolKeys(knipJson) {
const keys = new Set();
for (const entry of knipJson?.issues || []) {
for (const field of ["exports", "types", "nsExports", "nsTypes"]) {
for (const sym of entry[field] || []) keys.add(`${entry.file}:${sym.name}`);
}
}
for (const entry of knipJson?.issues || []) {
for (const f of entry.files || []) keys.add(`${f}:<file>`);
}
return keys;
}
/**
* Pure: dead symbols present on HEAD but not on the base, in files the PR touched — the
* only ones the PR is answerable for. A symbol that went dead in an UNTOUCHED file because
* the PR deleted its last consumer is also flagged when `includeUntouched` is set.
*/
export function newDeadSymbols(
headKnip,
baseKnip,
changedFiles,
{ includeUntouched = false } = {}
) {
const changed = new Set(changedFiles);
const base = deadSymbolKeys(baseKnip);
const out = [];
for (const key of deadSymbolKeys(headKnip)) {
if (base.has(key)) continue;
const file = key.slice(0, key.lastIndexOf(":"));
if (changed.has(file) || includeUntouched) out.push(key);
}
return out.sort();
}