#!/usr/bin/env node // scripts/quality/validate-release-green.mjs // // "Release-green" pre-flight validator (Solution C). // // WHY: the full gate (ci.yml — unit shards, vitest, ratchets, package-artifact) // runs ONLY on the release PR (PR → main). PRs into release/** only get the // fast-gates (quality.yml: TIA-impacted tests + typecheck + lint checks). So // reds accumulate silently on the release branch and explode — in layers — at // release time. This script reproduces the release-equivalent validation against // the CURRENT working tree so the maintainer (or the nightly, Solution D) can see // the real state of the release branch at any time. // // DESIGN — never blocking to contributors: // • HARD checks (typecheck, lint errors, db-rules, public-creds, docs-all, // unit, vitest, integration, optionally package-artifact) → a failure here is // a real defect; exit 1. // • DRIFT checks (eslint WARNINGS, cognitive-complexity, file-size, cyclomatic // complexity, dead-code, type-coverage, compression-budget, openapi-coverage, // workflow-lint/zizmor, codeql-ratchet) → ratchet drift accrued across the // cycle is NOT a contributor's fault; it is reported and rebaselined by the // maintainer at release. Drift NEVER changes the exit code, so wiring this as // a check can never block anyone on drift. // // COMPLETENESS: this mirrors the FULL release-PR gate set (quality-gate + // quality-extended + docs-sync-strict + integration), not a subset — and reports // EVERY red in one pass (the report is collected, not fail-fast), so the release // PR is green on its first CI run instead of revealing reds in ~40-min layers. The // only release-PR gates it cannot reproduce locally are GitHub-side CodeQL semantic // analysis and SonarQube/SonarCloud (external services). // // This script DIAGNOSES + REPORTS only (no auto-fix). The fix-to-green // orchestration lives in the /green-prs + review-prs flows that call it. // // Usage: // node scripts/quality/validate-release-green.mjs [--json] [--with-build] [--quick] [--full-ci] [--hermetic] // --json emit machine-readable JSON to stdout (report goes to stderr) // --with-build also run check:pack-artifact (needs a dist/ build — slow) // --quick skip the slow unit + vitest + integration suites (drift + fast // gates only) // --full-ci ALSO run every static gate declared in ci.yml's gate jobs (lint, // quality-gate, quality-extended, docs-sync-strict, pr-test-policy) — // read straight from ci.yml so the set never drifts. Catches the whole // "static base-red" category the curated list missed (v3.8.46: 11 of 16 // leaked reds). Pair with --quick for the fast "1 command, 0 CI layers" pass. // --hermetic scrub OMNIROUTE_API_KEY/OMNIROUTE_URL from gate env so live // tests self-skip exactly like CI (dev machines otherwise run // them against localhost and produce false-positive reds) // // Per-gate output is saved to _artifacts/release-green/.log (gitignored) — // diagnose a red from the file instead of re-running the gate. import { execFile, execFileSync } from "node:child_process"; import { promisify } from "node:util"; import { mkdirSync, readFileSync, writeFileSync } from "node:fs"; import { dirname, join } from "node:path"; import { fileURLToPath } from "node:url"; import { parse as parseYaml } from "yaml"; const __dirname = dirname(fileURLToPath(import.meta.url)); const ROOT = join(__dirname, "..", ".."); const npmCmd = process.platform === "win32" ? "npm.cmd" : "npm"; // Per-gate captured output. execFileSync buffers everything and the report only // shows a one-line summary, so without these files every red requires RE-RUNNING // the gate just to see the detail (the dominant cost of the 2026-07-05 pre-flight). const LOG_DIR = join(ROOT, "_artifacts", "release-green"); function saveGateLog(id, out) { try { mkdirSync(LOG_DIR, { recursive: true }); writeFileSync(join(LOG_DIR, `${id}.log`), String(out ?? "")); } catch { /* log persistence is best-effort — never fails a gate */ } } // ─── Pure helpers (exported for tests) ────────────────────────────────────── /** Read the committed ratchet baseline value for a metric (null if unknown). */ export function baselineValue(metric, root = ROOT) { try { const raw = JSON.parse( readFileSync(join(root, "config/quality/quality-baseline.json"), "utf8") ); const metrics = raw.metrics || raw; const v = metrics?.[metric]?.value; return typeof v === "number" ? v : null; } catch { return null; } } /** Best-effort "first meaningful failure line" from captured command output. */ export function firstFailureLine(out) { const lines = String(out || "") .split("\n") .map((l) => l.trim()) .filter(Boolean); const hit = lines.find((l) => /✖|✗|not ok|AssertionError|error TS|FAIL|Error:|REGRESS/i.test(l) ); return (hit || lines[lines.length - 1] || "failed").slice(0, 200); } /** Sum {errorCount,warningCount} across an eslint --format json result array. */ export function eslintCounts(parsed) { let errors = 0; let warnings = 0; for (const f of parsed || []) { errors += f.errorCount || 0; warnings += f.warningCount || 0; } return { errors, warnings }; } /** Parse the eslint JSON array out of mixed stdout (tolerates a leading banner). */ export function parseEslintJson(out) { const start = String(out || "").indexOf("["); if (start < 0) return null; try { return JSON.parse(String(out).slice(start)); } catch { return null; } } /** Pull the cognitive-complexity violation count from the gate's output. */ export function parseCognitiveCount(out) { const s = String(out || ""); // `check:complexity-ratchets` runs ONE shared ESLint walk and prints BOTH ratchets, with the // cyclomatic "N violações" summary emitted FIRST — so a bare `\d+ violações` regex would grab // the cyclomatic count. Prefer the unambiguous machine-readable `cognitiveComplexity=N` line // (mirrors the cyclomatic `complexity=N` parse used for cycCurrent below). const machine = s.match(/(?:^|\n)cognitiveComplexity=(\d+)/); if (machine) return Number(machine[1]); const m = s.match(/(\d+)\s+(?:function\(s\) exceed|violações|violations)/i); return m ? Number(m[1]) : null; } /** * Drift verdict for a ratchet: a metric that grew past its committed baseline is * "drift" (reported, never blocking). `direction:"down"` metrics (warnings, * complexity, file-size counts) regress when current > baseline. */ export function isDrift(current, baseline) { if (typeof current !== "number" || typeof baseline !== "number") return false; return current > baseline; } /** releaseGreen iff there are zero failing HARD checks (drift never blocks). */ export function computeVerdict(results) { const hardFailures = results.filter((r) => r.kind === "hard" && !r.ok); const drift = results.filter((r) => r.kind === "drift" && !r.ok); return { releaseGreen: hardFailures.length === 0, hardFailures, drift }; } // ─── --full-ci: reproduce the EXACT ci.yml gate set (P0, v3.8.46 post-mortem) ── // // WHY: the curated HARD/DRIFT lists above are a hand-maintained SUBSET. The v3.8.46 // release leaked 11 static/gate base-reds (route-validation:t06, docs-counts --strict, // docs-symbols, bundle-size --ratchet, test-masking, …) that the pre-flight never ran // because they live only in the ci.yml gate JOBS, not in this script. --full-ci reads // ci.yml itself and runs every `npm run check:*` / `npm run lint` from those jobs, so the // set stays current as gates are added (no drift between this script and CI). One command // → zero CI layers for the whole static category. /** ci.yml jobs whose npm-run gate steps --full-ci reproduces locally. */ export const FULL_CI_GATE_JOBS = [ "lint", "quality-gate", "quality-extended", "docs-sync-strict", "pr-test-policy", ]; // Gates that cannot run meaningfully in a local working-tree pre-flight: // • check:pr-evidence — inspects the open PR body (no PR locally) // • check:codeql-ratchet — queries GitHub's code-scanning alerts for the REMOTE main // branch (CodeQL Default Setup only analyzes main/PRs→main; a local run reflects // post-merge server state the pre-flight can't change). Checked on the release PR. export const FULL_CI_SKIP = new Set(["check:pr-evidence", "check:codeql-ratchet"]); // Gates that need a specific env to behave like CI (else they compare against the wrong base). export const FULL_CI_ENV = { "check:test-masking": { GITHUB_BASE_REF: "main" } }; /** * Parse a ci.yml text and return the ordered, de-duplicated list of gate commands to run. * Each entry: { id, job, args:["run",