@diffci.com/diffci 0.3.40 → 0.3.42
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
|
@@ -16,6 +16,7 @@
|
|
|
16
16
|
* check analysis plus automatic paired runtime measurement
|
|
17
17
|
* plan print Core's advisory JSON plan for a commit range (the input check-plan reads)
|
|
18
18
|
* check-plan compare a saved test selection with one full-suite JUnit result
|
|
19
|
+
* red-builds count a repository's red PR builds a check before the push could have prevented
|
|
19
20
|
* observe analyse the checkout and write an observation report
|
|
20
21
|
* verify-savings run a paired full-versus-selected timing check
|
|
21
22
|
* validate-specs block conflicting same-turn change specifications
|
|
@@ -61,6 +62,7 @@ import { buildPilotWorkflow, diffciVerificationWorkflow, diffciWorkflow } from "
|
|
|
61
62
|
import { buildMissReport, formatMissReportMarkdown, parseJunit } from "./enforce-misses.js";
|
|
62
63
|
import { appendOutcome, formatOutcomeSummary, outcomeLogPath, readOutcomes, summarizeOutcomes } from "./outcome-log.js";
|
|
63
64
|
import { checkPlan } from "./check-plan.js";
|
|
65
|
+
import { runRedBuildsCommand } from "./red-builds.js";
|
|
64
66
|
import { buildCoverageMap, formatCoverageRun } from "./coverage-map.js";
|
|
65
67
|
import { confidenceCurve, formatConfidenceCurve } from "./test-ranking.js";
|
|
66
68
|
import { parseShard, readTimings, timingsFromOutcomes } from "./test-shards.js";
|
|
@@ -1061,7 +1063,11 @@ function runVerifyWorkflow(flags, env) {
|
|
|
1061
1063
|
}
|
|
1062
1064
|
console.log(`Scanned ${result.workflowsScanned.length} workflow file(s).`);
|
|
1063
1065
|
if (result.observerJobs.length === 0) {
|
|
1064
|
-
|
|
1066
|
+
// Jobs that run DiffCI as a gate (verify, check-run, fail-on-error) are allowed to fail and are not
|
|
1067
|
+
// observers, but their warnings still belong in front of the user rather than behind this return.
|
|
1068
|
+
for (const finding of result.findings)
|
|
1069
|
+
console.log(formatFinding(finding));
|
|
1070
|
+
console.log("No job runs DiffCI as an observer (jobs that run it as a gate, with verify, check-run or fail-on-error, are allowed to fail and are not checked here). Add an observer job before starting the observation window.");
|
|
1065
1071
|
return 1;
|
|
1066
1072
|
}
|
|
1067
1073
|
console.log(`DiffCI runs in: ${result.observerJobs.join(", ")}`);
|
|
@@ -1412,6 +1418,7 @@ Usage:
|
|
|
1412
1418
|
[--redact-paths] [--json] [--quiet] [--fail-on-error] [--timeout-ms <ms>] [--share-usage]
|
|
1413
1419
|
diffci plan --base <sha> [--head <sha>] [--repo <path>]
|
|
1414
1420
|
diffci check-plan --plan <plan.json> --results <junit.xml>
|
|
1421
|
+
diffci red-builds <owner/repo> [--runs <n>] [--workflow <id|file>] [--json <file>]
|
|
1415
1422
|
diffci pilot --full <command> [--selected <command>] [--repo <path>] [--out-dir <dir>] [--label <name>]
|
|
1416
1423
|
diffci pilot-packet [--repo <path>] [--out-dir <dir>] [--base <sha> --head <sha>]
|
|
1417
1424
|
[--label <name>] [--repository-url <https-url>] [--redact-paths]
|
|
@@ -1533,6 +1540,11 @@ async function main() {
|
|
|
1533
1540
|
process.exitCode = await runPlanCommand(process.argv.slice(3));
|
|
1534
1541
|
return;
|
|
1535
1542
|
}
|
|
1543
|
+
// Stateless and read-only like check-plan: no shared flags, telemetry or feedback prompt.
|
|
1544
|
+
if (process.argv[2] === "red-builds") {
|
|
1545
|
+
process.exitCode = await runRedBuildsCommand(process.argv.slice(3));
|
|
1546
|
+
return;
|
|
1547
|
+
}
|
|
1536
1548
|
const { command, flags } = parseArgs(process.argv);
|
|
1537
1549
|
const env = process.env;
|
|
1538
1550
|
if (flags.help === true || command === "help" || command === undefined) {
|
|
@@ -0,0 +1,133 @@
|
|
|
1
|
+
export declare const RED_BUILDS_SCHEMA = 1;
|
|
2
|
+
export type JobBucket = "infra" | "ci-only" | "check";
|
|
3
|
+
export type Verdict = "preventable" | "partly" | "likely" | "shared" | "ci-only" | "flaky" | "infra";
|
|
4
|
+
export declare const VERDICTS: readonly Verdict[];
|
|
5
|
+
export interface RunSummary {
|
|
6
|
+
id: number;
|
|
7
|
+
workflowId: number;
|
|
8
|
+
workflowName: string;
|
|
9
|
+
attempt: number;
|
|
10
|
+
headSha: string;
|
|
11
|
+
headBranch: string;
|
|
12
|
+
headRepo: string;
|
|
13
|
+
conclusion: string | null;
|
|
14
|
+
createdAt: string;
|
|
15
|
+
}
|
|
16
|
+
export interface JobSummary {
|
|
17
|
+
id: number;
|
|
18
|
+
name: string;
|
|
19
|
+
conclusion: string | null;
|
|
20
|
+
startedAt: string | null;
|
|
21
|
+
completedAt: string | null;
|
|
22
|
+
failedSteps: string[];
|
|
23
|
+
}
|
|
24
|
+
export interface Annotation {
|
|
25
|
+
path: string | null;
|
|
26
|
+
title: string | null;
|
|
27
|
+
message: string | null;
|
|
28
|
+
level: string | null;
|
|
29
|
+
}
|
|
30
|
+
export interface Patterns {
|
|
31
|
+
checkJob: RegExp;
|
|
32
|
+
ciOnlyJob: RegExp;
|
|
33
|
+
}
|
|
34
|
+
export declare const DEFAULT_PATTERNS: Patterns;
|
|
35
|
+
export declare function bucketJob(job: JobSummary, patterns?: Patterns): JobBucket;
|
|
36
|
+
export declare function isAggregateJob(job: JobSummary): boolean;
|
|
37
|
+
/** Failure signatures of one job: annotation path, title and first message line, with volatile parts blurred. */
|
|
38
|
+
export declare function signatures(annotations: Annotation[]): Set<string>;
|
|
39
|
+
export interface RedRun {
|
|
40
|
+
run: number;
|
|
41
|
+
workflow: string;
|
|
42
|
+
attempt: number;
|
|
43
|
+
fork: boolean;
|
|
44
|
+
verdict: Verdict;
|
|
45
|
+
failingJobs: Array<{
|
|
46
|
+
name: string;
|
|
47
|
+
bucket: JobBucket;
|
|
48
|
+
ownership?: "own" | "shared" | "timeout" | "unknown";
|
|
49
|
+
}>;
|
|
50
|
+
runnerMinutes: number;
|
|
51
|
+
agent?: {
|
|
52
|
+
written: boolean;
|
|
53
|
+
marker: string;
|
|
54
|
+
commitRead: boolean;
|
|
55
|
+
};
|
|
56
|
+
}
|
|
57
|
+
export interface ClassifyInput {
|
|
58
|
+
repository: string;
|
|
59
|
+
runs: RunSummary[];
|
|
60
|
+
/** Jobs of the latest attempt of each red run, by run id. Missing: the job list could not be read. */
|
|
61
|
+
jobs: Map<number, JobSummary[]>;
|
|
62
|
+
/** Failure annotations by job id. Missing: not fetched or unreadable. */
|
|
63
|
+
annotations: Map<number, Annotation[]>;
|
|
64
|
+
patterns?: Patterns;
|
|
65
|
+
}
|
|
66
|
+
/** Pure: sorts every red run whose jobs were read into one verdict. */
|
|
67
|
+
export declare function classify(input: ClassifyInput): RedRun[];
|
|
68
|
+
export declare function agentMarker(message: string, branch: string): {
|
|
69
|
+
written: boolean;
|
|
70
|
+
marker: string;
|
|
71
|
+
};
|
|
72
|
+
export interface RedBuildsReport {
|
|
73
|
+
schemaVersion: typeof RED_BUILDS_SCHEMA;
|
|
74
|
+
repository: string;
|
|
75
|
+
/** The workflow whose pull request runs were read. */
|
|
76
|
+
workflow: string | null;
|
|
77
|
+
window: {
|
|
78
|
+
from: string;
|
|
79
|
+
to: string;
|
|
80
|
+
} | null;
|
|
81
|
+
pullRequestRuns: number;
|
|
82
|
+
redRuns: number;
|
|
83
|
+
analysed: number;
|
|
84
|
+
unreadable: number;
|
|
85
|
+
verdicts: Record<Verdict, {
|
|
86
|
+
runs: number;
|
|
87
|
+
runnerMinutes: number;
|
|
88
|
+
}>;
|
|
89
|
+
agentWrittenPreventable: number;
|
|
90
|
+
stoppedEarly: string | null;
|
|
91
|
+
rows: RedRun[];
|
|
92
|
+
}
|
|
93
|
+
export declare function summarise(repository: string, runs: RunSummary[], rows: RedRun[], stoppedEarly: string | null): RedBuildsReport;
|
|
94
|
+
export declare function formatReport(report: RedBuildsReport): string;
|
|
95
|
+
export type GitHubGet = (path: string) => Promise<{
|
|
96
|
+
status: number;
|
|
97
|
+
body: unknown;
|
|
98
|
+
}>;
|
|
99
|
+
export declare class StopCollection extends Error {
|
|
100
|
+
}
|
|
101
|
+
/** Paced, read-only GitHub REST client: >= 1.2 s between calls, stops on Retry-After or a low quota. */
|
|
102
|
+
export declare function githubClient(token: string, options?: {
|
|
103
|
+
minIntervalMs?: number;
|
|
104
|
+
minRemaining?: number;
|
|
105
|
+
fetchFn?: typeof fetch;
|
|
106
|
+
sleep?: (ms: number) => Promise<void>;
|
|
107
|
+
}): GitHubGet;
|
|
108
|
+
/**
|
|
109
|
+
* The main pull request CI among one sample page of runs: wall-clock minutes per workflow, doubled when
|
|
110
|
+
* its name or file looks like CI and cut to 5% when it looks like a scanner, preview, benchmark or bot.
|
|
111
|
+
* Plain "most minutes" picked SonarQube, Benchmarks and preview builds on real repositories.
|
|
112
|
+
*/
|
|
113
|
+
export declare function pickMainWorkflow(sample: any[]): {
|
|
114
|
+
id: number;
|
|
115
|
+
name: string;
|
|
116
|
+
path: string;
|
|
117
|
+
} | undefined;
|
|
118
|
+
export interface CollectOptions {
|
|
119
|
+
repository: string;
|
|
120
|
+
get: GitHubGet;
|
|
121
|
+
maxRuns: number;
|
|
122
|
+
workflow?: string;
|
|
123
|
+
patterns?: Patterns;
|
|
124
|
+
log?: (line: string) => void;
|
|
125
|
+
}
|
|
126
|
+
/** Fetches runs, jobs, annotations and commit messages, then classifies. Partial data on a stop. */
|
|
127
|
+
export declare function collectRedBuilds(options: CollectOptions): Promise<RedBuildsReport>;
|
|
128
|
+
export declare function resolveGitHubToken(env: NodeJS.ProcessEnv): string | undefined;
|
|
129
|
+
export declare const RED_BUILDS_USAGE = "Usage: diffci red-builds <owner/repo> [--runs <n>] [--workflow <id|file>] [--json <file>]\n [--check-jobs <regex>] [--ci-only-jobs <regex>]\nHow many of a repository's red pull request builds failed on checks the author could have run before\npushing. Reads GitHub Actions history (read-only, paced) and runs nothing. Needs a GitHub token:\nGITHUB_TOKEN, GH_TOKEN, or a signed-in gh CLI. --runs: most recent pull request runs to read (default 200,\nmax 1000). --check-jobs / --ci-only-jobs: regexes that override which job names count as local checks.";
|
|
130
|
+
/** Entry point for `diffci red-builds`. Returns the exit code: 0 on a report, 2 on bad input or errors. */
|
|
131
|
+
export declare function runRedBuildsCommand(args: string[], env?: NodeJS.ProcessEnv, deps?: {
|
|
132
|
+
get?: GitHubGet;
|
|
133
|
+
}): Promise<number>;
|
|
@@ -0,0 +1,507 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `diffci red-builds <owner/repo>`: how many of a repository's red pull request builds failed on checks the
|
|
3
|
+
* author (or their coding agent) could have run before pushing.
|
|
4
|
+
*
|
|
5
|
+
* It reads CI history only, through GitHub's REST API, and runs nothing. For the most recent pull request
|
|
6
|
+
* workflow runs it fetches the job list of every red run, the failure annotations of each failing check job,
|
|
7
|
+
* and, for the runs it judges preventable, the head commit message (to spot agent co-author trailers).
|
|
8
|
+
*
|
|
9
|
+
* How a red run is judged (method of the Sentry and Paperclip studies, 2026-11-11):
|
|
10
|
+
* - Each failing job is `infra` (only setup/install/cache steps failed, or no step failed: cancelled or
|
|
11
|
+
* timed out), `ci-only` (E2E, browser, deploy, release, lockfile and similar jobs no local check runs),
|
|
12
|
+
* or `check` (lint, format, typecheck, build, unit and integration tests). Names that match neither count
|
|
13
|
+
* as ci-only, so an unknown job can never inflate the preventable count.
|
|
14
|
+
* - A failing check job is the PR's `own` failure when none of its annotation signatures (file + first
|
|
15
|
+
* message line, numbers and hashes blurred) also failed on a different PR in the window. A signature seen
|
|
16
|
+
* on several PRs is `shared`: a broken base branch or a test that fails for everyone, not this change.
|
|
17
|
+
* - preventable: every failing job is an own check failure. partly: an own check failure next to other
|
|
18
|
+
* failures. likely: check failures with no annotations to confirm whose they are. flaky: the same head
|
|
19
|
+
* commit later passed in the same workflow.
|
|
20
|
+
*
|
|
21
|
+
* Every figure is an upper bound: it assumes the author ran the check and that it included the failing
|
|
22
|
+
* test. Pacing follows DiffCI's outreach rules: authenticated, one call at a time, at least 1.2 s apart,
|
|
23
|
+
* stop on Retry-After or when fewer than 1,000 calls remain in the hour.
|
|
24
|
+
*/
|
|
25
|
+
import { spawnSync } from "node:child_process";
|
|
26
|
+
import { writeFileSync } from "node:fs";
|
|
27
|
+
export const RED_BUILDS_SCHEMA = 1;
|
|
28
|
+
const REPOSITORY = /^[A-Za-z0-9][A-Za-z0-9-]{0,38}\/[A-Za-z0-9._-]{1,100}$/;
|
|
29
|
+
const INFRA_STEP = /set up|setup|checkout|install|cache|download|upload|restore|docker|login|post /i;
|
|
30
|
+
/** Jobs no local check can stand in for, whatever else the name says ("e2e tests" is not a unit test). */
|
|
31
|
+
const CI_ONLY_STRONG = /\b(e2e|end[- ]to[- ]end|playwright|cypress|puppeteer|selenium|browserstack|deploy(ment)?|preview|docker|lighthouse|chromatic|percy|visual)\b/i;
|
|
32
|
+
/** CI-side jobs that lose to a check word: "Typecheck + Release Registry" is still a typecheck. */
|
|
33
|
+
const CI_ONLY_JOB = /\b(release|publish|image|container|bench(mark)?s?|perf(ormance)?|size[- ]?(limit|check)?|bundle[- ]?size|codeql|security|snyk|dependency[- ]review|licen[cs]e|label(er)?|stale|triage|storybook|cla|dco|semantic|pr[- ]title|changeset|lockfile|danger|codecov|coverage[- ]upload|vercel|netlify|sonar)\b/i;
|
|
34
|
+
const CHECK_JOB = /\b(lint(ing)?|eslint|biome|prettier|format(ting)?|fmt|style|typecheck|type[- ]?check(ing)?|types|tsc|mypy|pyright|clippy|vet|build|compile|unit|tests?|suites?|vitest|jest|mocha|pytest|spec|integration|check)\b/i;
|
|
35
|
+
/** Aggregate gate jobs ("all required jobs passed"): they fail because another job did, so they are ignored
|
|
36
|
+
* whenever another job in the same run failed too. */
|
|
37
|
+
const AGGREGATE_JOB = /^(verify|gate|ci|required|all[- ]?(required|checks|jobs|green)?([- ]?(passed|pass|green|ok))?|ci[- ]?(ok|success|passed|status|result)|status|summary|results?|conclusion|done|complete|finish(ed)?|success|alls-green|check[- ]results?)$/i;
|
|
38
|
+
const CI_ONLY_STEP = /lockfile|lock file|migration ordering/i;
|
|
39
|
+
const GENERIC_ANNOTATION = /process completed with exit code|^command failed|elifecycle|exited with code/i;
|
|
40
|
+
const TIMEOUT = /timed out|timeout/i;
|
|
41
|
+
const AGENT_TRAILER = /co-authored-by:[^\n]*?\b(claude|cursor|copilot|codex|devin|openai|anthropic|jules|aider|windsurf)\b|generated with \[?(claude code|codex)/i;
|
|
42
|
+
const AGENT_BRANCH = /^(claude|codex|copilot|cursor|devin|jules)[/-]/i;
|
|
43
|
+
export const VERDICTS = ["preventable", "partly", "likely", "shared", "ci-only", "flaky", "infra"];
|
|
44
|
+
export const DEFAULT_PATTERNS = { checkJob: CHECK_JOB, ciOnlyJob: CI_ONLY_JOB };
|
|
45
|
+
export function bucketJob(job, patterns = DEFAULT_PATTERNS) {
|
|
46
|
+
if (job.failedSteps.length === 0)
|
|
47
|
+
return "infra"; // cancelled, timed out or runner lost: no step failed
|
|
48
|
+
if (job.failedSteps.every((step) => INFRA_STEP.test(step)))
|
|
49
|
+
return "infra";
|
|
50
|
+
if (job.failedSteps.every((step) => CI_ONLY_STEP.test(step)))
|
|
51
|
+
return "ci-only";
|
|
52
|
+
// The job's own name, without a "Workflow / " prefix, decides. CI-only wins so "e2e tests" is not a check.
|
|
53
|
+
const name = jobName(job);
|
|
54
|
+
// A --ci-only-jobs override wins outright; by default only the strong CI-only words beat a check word.
|
|
55
|
+
const ciOnlyFirst = patterns.ciOnlyJob === CI_ONLY_JOB ? CI_ONLY_STRONG : patterns.ciOnlyJob;
|
|
56
|
+
if (ciOnlyFirst.test(name))
|
|
57
|
+
return "ci-only";
|
|
58
|
+
if (patterns.checkJob.test(name))
|
|
59
|
+
return "check";
|
|
60
|
+
return "ci-only"; // a CI-side job by name, or one matching neither list: never inflates the preventable count
|
|
61
|
+
}
|
|
62
|
+
/** The job's own name, without a "Workflow / " or "caller / " prefix. */
|
|
63
|
+
function jobName(job) {
|
|
64
|
+
return (job.name.split(" / ").at(-1) ?? job.name).trim();
|
|
65
|
+
}
|
|
66
|
+
export function isAggregateJob(job) {
|
|
67
|
+
return AGGREGATE_JOB.test(jobName(job).replace(/[()]/g, "").trim());
|
|
68
|
+
}
|
|
69
|
+
/** Failure signatures of one job: annotation path, title and first message line, with volatile parts blurred. */
|
|
70
|
+
export function signatures(annotations) {
|
|
71
|
+
const out = new Set();
|
|
72
|
+
for (const a of annotations) {
|
|
73
|
+
if (a.level !== "failure")
|
|
74
|
+
continue;
|
|
75
|
+
const first = (a.message ?? "").trim().split(/\r?\n/)[0] ?? "";
|
|
76
|
+
if (GENERIC_ANNOTATION.test(first) || (!first && !a.title))
|
|
77
|
+
continue;
|
|
78
|
+
if (!a.path || a.path === ".github")
|
|
79
|
+
continue; // runner-level messages, not a test or lint failure
|
|
80
|
+
const text = `${a.path} :: ${a.title ?? ""} :: ${first}`.replace(/\/tmp\/\S+|[0-9a-f]{7,}|\d+(\.\d+)?/g, "#");
|
|
81
|
+
out.add(text.slice(0, 300));
|
|
82
|
+
}
|
|
83
|
+
return out;
|
|
84
|
+
}
|
|
85
|
+
function minutes(job) {
|
|
86
|
+
if (!job.startedAt || !job.completedAt)
|
|
87
|
+
return 0;
|
|
88
|
+
return Math.max(0, (Date.parse(job.completedAt) - Date.parse(job.startedAt)) / 60_000);
|
|
89
|
+
}
|
|
90
|
+
/** Pure: sorts every red run whose jobs were read into one verdict. */
|
|
91
|
+
export function classify(input) {
|
|
92
|
+
const patterns = input.patterns ?? DEFAULT_PATTERNS;
|
|
93
|
+
const passed = new Set(input.runs.filter((r) => r.conclusion === "success").map((r) => `${r.workflowId}:${r.headSha}`));
|
|
94
|
+
const prKey = (r) => `${r.headRepo}:${r.headBranch}`;
|
|
95
|
+
const failingOf = (jobs) => jobs.filter((j) => j.conclusion === "failure" || j.conclusion === "timed_out");
|
|
96
|
+
// Which PRs each failure signature appeared on, across the whole window.
|
|
97
|
+
const seen = new Map();
|
|
98
|
+
for (const run of input.runs) {
|
|
99
|
+
const jobs = input.jobs.get(run.id);
|
|
100
|
+
if (run.conclusion !== "failure" || !jobs)
|
|
101
|
+
continue;
|
|
102
|
+
for (const job of failingOf(jobs)) {
|
|
103
|
+
if (bucketJob(job, patterns) !== "check")
|
|
104
|
+
continue;
|
|
105
|
+
for (const sig of signatures(input.annotations.get(job.id) ?? [])) {
|
|
106
|
+
if (!seen.has(sig))
|
|
107
|
+
seen.set(sig, new Set());
|
|
108
|
+
seen.get(sig).add(prKey(run));
|
|
109
|
+
}
|
|
110
|
+
}
|
|
111
|
+
}
|
|
112
|
+
const rows = [];
|
|
113
|
+
for (const run of input.runs) {
|
|
114
|
+
const jobs = input.jobs.get(run.id);
|
|
115
|
+
if (run.conclusion !== "failure" || !jobs)
|
|
116
|
+
continue;
|
|
117
|
+
const allFailing = failingOf(jobs);
|
|
118
|
+
// A gate job that only reports "something else failed" says nothing on its own.
|
|
119
|
+
const failing = allFailing.some((j) => !isAggregateJob(j)) ? allFailing.filter((j) => !isAggregateJob(j)) : allFailing;
|
|
120
|
+
const detail = failing.map((job) => {
|
|
121
|
+
const bucket = bucketJob(job, patterns);
|
|
122
|
+
if (bucket !== "check")
|
|
123
|
+
return { name: job.name, bucket };
|
|
124
|
+
const annotations = input.annotations.get(job.id);
|
|
125
|
+
const sigs = signatures(annotations ?? []);
|
|
126
|
+
let ownership;
|
|
127
|
+
if (sigs.size === 0)
|
|
128
|
+
ownership = "unknown";
|
|
129
|
+
else if ([...sigs].every((s) => TIMEOUT.test(s)))
|
|
130
|
+
ownership = "timeout";
|
|
131
|
+
else if ([...sigs].some((s) => !TIMEOUT.test(s) && (seen.get(s)?.size ?? 0) > 1))
|
|
132
|
+
ownership = "shared";
|
|
133
|
+
else
|
|
134
|
+
ownership = "own";
|
|
135
|
+
return { name: job.name, bucket, ownership };
|
|
136
|
+
});
|
|
137
|
+
const real = detail.filter((d) => d.bucket !== "infra");
|
|
138
|
+
const checks = real.filter((d) => d.bucket === "check");
|
|
139
|
+
const ciOnly = real.some((d) => d.bucket === "ci-only");
|
|
140
|
+
let verdict;
|
|
141
|
+
if (real.length === 0)
|
|
142
|
+
verdict = "infra";
|
|
143
|
+
else if (passed.has(`${run.workflowId}:${run.headSha}`))
|
|
144
|
+
verdict = "flaky";
|
|
145
|
+
else if (checks.length === 0)
|
|
146
|
+
verdict = "ci-only";
|
|
147
|
+
else if (checks.every((d) => d.ownership === "own") && !ciOnly)
|
|
148
|
+
verdict = "preventable";
|
|
149
|
+
else if (checks.some((d) => d.ownership === "own"))
|
|
150
|
+
verdict = "partly";
|
|
151
|
+
else if (checks.every((d) => d.ownership === "unknown") && !ciOnly)
|
|
152
|
+
verdict = "likely";
|
|
153
|
+
else if (checks.some((d) => d.ownership === "shared"))
|
|
154
|
+
verdict = "shared";
|
|
155
|
+
else
|
|
156
|
+
verdict = ciOnly ? "ci-only" : "likely";
|
|
157
|
+
rows.push({
|
|
158
|
+
run: run.id,
|
|
159
|
+
workflow: run.workflowName,
|
|
160
|
+
attempt: run.attempt,
|
|
161
|
+
fork: run.headRepo !== input.repository,
|
|
162
|
+
verdict,
|
|
163
|
+
failingJobs: detail,
|
|
164
|
+
runnerMinutes: Math.round(jobs.reduce((sum, job) => sum + minutes(job), 0) * 10) / 10,
|
|
165
|
+
});
|
|
166
|
+
}
|
|
167
|
+
return rows;
|
|
168
|
+
}
|
|
169
|
+
export function agentMarker(message, branch) {
|
|
170
|
+
const trailer = AGENT_TRAILER.exec(message);
|
|
171
|
+
if (trailer)
|
|
172
|
+
return { written: true, marker: (trailer[1] ?? trailer[2] ?? "agent").toLowerCase() };
|
|
173
|
+
if (AGENT_BRANCH.test(branch))
|
|
174
|
+
return { written: true, marker: "branch prefix" };
|
|
175
|
+
return { written: false, marker: "" };
|
|
176
|
+
}
|
|
177
|
+
export function summarise(repository, runs, rows, stoppedEarly) {
|
|
178
|
+
const verdicts = Object.fromEntries(VERDICTS.map((v) => [v, { runs: 0, runnerMinutes: 0 }]));
|
|
179
|
+
for (const row of rows) {
|
|
180
|
+
verdicts[row.verdict].runs++;
|
|
181
|
+
verdicts[row.verdict].runnerMinutes += row.runnerMinutes;
|
|
182
|
+
}
|
|
183
|
+
for (const v of VERDICTS)
|
|
184
|
+
verdicts[v].runnerMinutes = Math.round(verdicts[v].runnerMinutes);
|
|
185
|
+
const times = runs.map((r) => r.createdAt).sort();
|
|
186
|
+
const red = runs.filter((r) => r.conclusion === "failure").length;
|
|
187
|
+
return {
|
|
188
|
+
schemaVersion: RED_BUILDS_SCHEMA,
|
|
189
|
+
repository,
|
|
190
|
+
workflow: runs[0]?.workflowName ?? null,
|
|
191
|
+
window: times.length ? { from: times[0], to: times.at(-1) } : null,
|
|
192
|
+
pullRequestRuns: runs.length,
|
|
193
|
+
redRuns: red,
|
|
194
|
+
analysed: rows.length,
|
|
195
|
+
unreadable: red - rows.length,
|
|
196
|
+
verdicts,
|
|
197
|
+
agentWrittenPreventable: rows.filter((r) => r.verdict === "preventable" && r.agent?.written).length,
|
|
198
|
+
stoppedEarly,
|
|
199
|
+
rows,
|
|
200
|
+
};
|
|
201
|
+
}
|
|
202
|
+
const LABELS = {
|
|
203
|
+
preventable: "Preventable before the push",
|
|
204
|
+
partly: "Partly preventable",
|
|
205
|
+
likely: "Likely preventable (unconfirmed)",
|
|
206
|
+
shared: "Shared with other PRs",
|
|
207
|
+
"ci-only": "CI-only (E2E, deploy, lockfile...)",
|
|
208
|
+
flaky: "Flaky (same commit passed later)",
|
|
209
|
+
infra: "Infrastructure (setup, cancelled)",
|
|
210
|
+
};
|
|
211
|
+
const NOTES = {
|
|
212
|
+
preventable: "the PR's own lint, type, build or test failure",
|
|
213
|
+
likely: "check jobs failed, but no annotations say whose",
|
|
214
|
+
shared: "the same failure on other PRs: a broken base, not this change",
|
|
215
|
+
};
|
|
216
|
+
function pct(part, whole) {
|
|
217
|
+
return whole ? `${Math.round((part / whole) * 100)}%` : "0%";
|
|
218
|
+
}
|
|
219
|
+
export function formatReport(report) {
|
|
220
|
+
const lines = [`DiffCI red-build check: ${report.repository}${report.workflow ? ` · workflow "${report.workflow}"` : ""}`];
|
|
221
|
+
if (!report.window) {
|
|
222
|
+
lines.push("", "No pull request workflow runs found.");
|
|
223
|
+
return lines.join("\n");
|
|
224
|
+
}
|
|
225
|
+
lines.push(`${report.window.from.slice(0, 16).replace("T", " ")} to ${report.window.to.slice(0, 16).replace("T", " ")} UTC · ${report.pullRequestRuns} pull request runs, ${report.redRuns} red (${pct(report.redRuns, report.pullRequestRuns)})`);
|
|
226
|
+
if (report.unreadable > 0)
|
|
227
|
+
lines.push(`${report.unreadable} red runs could not be read and are left out.`);
|
|
228
|
+
if (report.analysed === 0) {
|
|
229
|
+
lines.push("", "No red runs to analyse.");
|
|
230
|
+
return lines.join("\n");
|
|
231
|
+
}
|
|
232
|
+
lines.push("", `${"Red runs by cause".padEnd(38)}${"runs".padStart(6)}${"runner-min".padStart(12)}`);
|
|
233
|
+
for (const v of VERDICTS) {
|
|
234
|
+
const { runs, runnerMinutes } = report.verdicts[v];
|
|
235
|
+
if (runs === 0 && v !== "preventable")
|
|
236
|
+
continue;
|
|
237
|
+
const note = NOTES[v] ? ` ${NOTES[v]}` : "";
|
|
238
|
+
lines.push(` ${LABELS[v].padEnd(36)}${String(runs).padStart(6)}${runnerMinutes.toLocaleString("en-US").padStart(12)}${note}`);
|
|
239
|
+
if (v === "preventable" && runs > 0)
|
|
240
|
+
lines.push(` ${"written by a coding agent".padEnd(34)}${String(report.agentWrittenPreventable).padStart(6)}`);
|
|
241
|
+
}
|
|
242
|
+
const p = report.verdicts.preventable.runs;
|
|
243
|
+
const likely = report.verdicts.likely.runs;
|
|
244
|
+
lines.push("", `Up to ${p} of ${report.analysed} red runs (${pct(p, report.analysed)}) failed only on checks the author could have run before pushing.`, ...(likely ? [`${likely} more failed on such checks without annotations, so whose failure it was is unconfirmed.`] : []), "That is an upper bound: it assumes the check ran and covered the failing test. CI history only; nothing was run.", "", "Catch these inside your coding agent's loop, before the push: npx @diffci.com/diffci init", "Method: https://github.com/DiffCI/core/blob/main/docs/red-builds.md");
|
|
245
|
+
if (report.stoppedEarly)
|
|
246
|
+
lines.push("", `Stopped early: ${report.stoppedEarly}. The figures cover what was read.`);
|
|
247
|
+
return lines.join("\n");
|
|
248
|
+
}
|
|
249
|
+
export class StopCollection extends Error {
|
|
250
|
+
}
|
|
251
|
+
/** Paced, read-only GitHub REST client: >= 1.2 s between calls, stops on Retry-After or a low quota. */
|
|
252
|
+
export function githubClient(token, options = {}) {
|
|
253
|
+
const interval = options.minIntervalMs ?? 1200;
|
|
254
|
+
const floor = options.minRemaining ?? 1000;
|
|
255
|
+
const fetchFn = options.fetchFn ?? fetch;
|
|
256
|
+
const sleep = options.sleep ?? ((ms) => new Promise((resolve) => setTimeout(resolve, ms)));
|
|
257
|
+
let last = 0;
|
|
258
|
+
return async (path) => {
|
|
259
|
+
const wait = last + interval - Date.now();
|
|
260
|
+
if (wait > 0)
|
|
261
|
+
await sleep(wait);
|
|
262
|
+
last = Date.now();
|
|
263
|
+
const request = () => fetchFn(`https://api.github.com/${path}`, {
|
|
264
|
+
headers: { Accept: "application/vnd.github+json", Authorization: `Bearer ${token}`, "User-Agent": "diffci-red-builds", "X-GitHub-Api-Version": "2022-11-28" },
|
|
265
|
+
});
|
|
266
|
+
let res;
|
|
267
|
+
try {
|
|
268
|
+
res = await request();
|
|
269
|
+
}
|
|
270
|
+
catch {
|
|
271
|
+
// A dropped connection ("fetch failed"), not a GitHub answer: one slow retry, then give up.
|
|
272
|
+
await sleep(10_000);
|
|
273
|
+
last = Date.now();
|
|
274
|
+
res = await request();
|
|
275
|
+
}
|
|
276
|
+
if (res.headers.get("retry-after"))
|
|
277
|
+
throw new StopCollection(`GitHub asked to slow down (Retry-After on ${path.split("?")[0]})`);
|
|
278
|
+
const remaining = Number(res.headers.get("x-ratelimit-remaining") ?? "Infinity");
|
|
279
|
+
const body = res.status === 204 ? undefined : await res.json().catch(() => undefined);
|
|
280
|
+
if (res.status === 401)
|
|
281
|
+
throw new Error("GitHub rejected the token (401)");
|
|
282
|
+
if (res.status === 403 && remaining === 0)
|
|
283
|
+
throw new StopCollection("the hourly GitHub API quota is used up");
|
|
284
|
+
if (remaining < floor)
|
|
285
|
+
throw new StopCollection(`fewer than ${floor} GitHub API calls left this hour`);
|
|
286
|
+
return { status: res.status, body };
|
|
287
|
+
};
|
|
288
|
+
}
|
|
289
|
+
/** Workflows that run on pull requests but are not the test CI: scanners, previews, benchmarks, bots. */
|
|
290
|
+
const NOT_MAIN_WORKFLOW = /\b(preview|codeql|security|semgrep|sonar(qube|cloud)?|snyk|scorecard|bench(mark)?s?|size|label(er|s)?|stale|triage|greet(ings?)?|welcome|translations?|i18n|docs?|documentation|docker|image|deploy(ment)?|release|licen[cs]e|title|conventional|commits?|semantic|submodule|e2e|playwright|cypress|lighthouse|dependabot|renovate|cla|dco|changeset|storybook|chromatic)\b/i;
|
|
291
|
+
/** Names and file names the main pull request CI usually has. */
|
|
292
|
+
const MAIN_WORKFLOW = /\b(ci|cd|tests?|pipeline|pr|pull[-_ ]request|build|checks?|main|verify|validate|unit|lint|quality)\b/i;
|
|
293
|
+
/**
|
|
294
|
+
* The main pull request CI among one sample page of runs: wall-clock minutes per workflow, doubled when
|
|
295
|
+
* its name or file looks like CI and cut to 5% when it looks like a scanner, preview, benchmark or bot.
|
|
296
|
+
* Plain "most minutes" picked SonarQube, Benchmarks and preview builds on real repositories.
|
|
297
|
+
*/
|
|
298
|
+
export function pickMainWorkflow(sample) {
|
|
299
|
+
const weight = new Map();
|
|
300
|
+
for (const r of sample) {
|
|
301
|
+
const span = (Date.parse(r.updated_at) - Date.parse(r.run_started_at ?? r.created_at)) / 60_000;
|
|
302
|
+
const path = String(r.path ?? "").replace(/^\.github\/workflows\//, "");
|
|
303
|
+
const entry = weight.get(r.workflow_id) ?? { name: String(r.name ?? r.workflow_id), path, minutes: 0 };
|
|
304
|
+
entry.minutes += Number.isFinite(span) && span > 0 ? span : 0;
|
|
305
|
+
weight.set(r.workflow_id, entry);
|
|
306
|
+
}
|
|
307
|
+
let best;
|
|
308
|
+
for (const [id, w] of weight) {
|
|
309
|
+
const text = `${w.name} ${w.path.replace(/\.ya?ml$/, "").replace(/[-_.]/g, " ")}`;
|
|
310
|
+
const score = (w.minutes + 0.01) * (NOT_MAIN_WORKFLOW.test(text) ? 0.05 : 1) * (MAIN_WORKFLOW.test(text) ? 2 : 1);
|
|
311
|
+
if (!best || score > best.score)
|
|
312
|
+
best = { id, name: w.name, path: w.path, score };
|
|
313
|
+
}
|
|
314
|
+
return best && { id: best.id, name: best.name, path: best.path };
|
|
315
|
+
}
|
|
316
|
+
/** Fetches runs, jobs, annotations and commit messages, then classifies. Partial data on a stop. */
|
|
317
|
+
export async function collectRedBuilds(options) {
|
|
318
|
+
const { repository, get } = options;
|
|
319
|
+
const log = options.log ?? (() => undefined);
|
|
320
|
+
const patterns = options.patterns ?? DEFAULT_PATTERNS;
|
|
321
|
+
const runs = [];
|
|
322
|
+
const jobs = new Map();
|
|
323
|
+
const annotations = new Map();
|
|
324
|
+
let stoppedEarly = null;
|
|
325
|
+
let workflow = options.workflow;
|
|
326
|
+
let workflowLabel = workflow ?? "";
|
|
327
|
+
try {
|
|
328
|
+
if (!workflow) {
|
|
329
|
+
// Default: the heaviest pull request workflow (most wall-clock time in one sample page), which is the
|
|
330
|
+
// main CI in practice. Counting runs of every workflow lets labelers and bots flood the window.
|
|
331
|
+
const { status, body } = await get(`repos/${repository}/actions/runs?event=pull_request&per_page=100`);
|
|
332
|
+
if (status === 404)
|
|
333
|
+
throw new Error(`${repository} not found, or its Actions history is not visible to this token`);
|
|
334
|
+
if (status !== 200)
|
|
335
|
+
throw new Error(`listing workflow runs failed (HTTP ${status})`);
|
|
336
|
+
const chosen = pickMainWorkflow(body?.workflow_runs ?? []);
|
|
337
|
+
if (!chosen)
|
|
338
|
+
return summarise(repository, [], [], null);
|
|
339
|
+
workflow = String(chosen.id);
|
|
340
|
+
workflowLabel = chosen.name;
|
|
341
|
+
log(`Using the "${workflowLabel}" workflow (${chosen.path}), which looks like the main pull request CI. Pass --workflow to choose another.`);
|
|
342
|
+
}
|
|
343
|
+
const base = `repos/${repository}/actions/workflows/${encodeURIComponent(workflow)}/runs`;
|
|
344
|
+
for (let page = 1; runs.length < options.maxRuns; page++) {
|
|
345
|
+
const { status, body } = await get(`${base}?event=pull_request&per_page=100&page=${page}`);
|
|
346
|
+
if (status === 404)
|
|
347
|
+
throw new Error(`${repository} workflow ${workflow} not found, or its Actions history is not visible to this token`);
|
|
348
|
+
if (status !== 200)
|
|
349
|
+
throw new Error(`listing workflow runs failed (HTTP ${status})`);
|
|
350
|
+
const batch = (body?.workflow_runs ?? []);
|
|
351
|
+
for (const r of batch.slice(0, options.maxRuns - runs.length)) {
|
|
352
|
+
runs.push({
|
|
353
|
+
id: r.id, workflowId: r.workflow_id, workflowName: String(r.name ?? ""), attempt: r.run_attempt ?? 1,
|
|
354
|
+
headSha: r.head_sha, headBranch: String(r.head_branch ?? ""), headRepo: String(r.head_repository?.full_name ?? ""),
|
|
355
|
+
conclusion: r.conclusion ?? null, createdAt: r.created_at,
|
|
356
|
+
});
|
|
357
|
+
}
|
|
358
|
+
if (batch.length < 100)
|
|
359
|
+
break;
|
|
360
|
+
}
|
|
361
|
+
const red = runs.filter((r) => r.conclusion === "failure");
|
|
362
|
+
log(`${runs.length} pull request runs, ${red.length} red. Reading their jobs...`);
|
|
363
|
+
for (const run of red) {
|
|
364
|
+
const list = [];
|
|
365
|
+
let readable = true;
|
|
366
|
+
for (let page = 1;; page++) {
|
|
367
|
+
const { status, body } = await get(`repos/${repository}/actions/runs/${run.id}/attempts/${run.attempt}/jobs?per_page=100&page=${page}`);
|
|
368
|
+
if (status !== 200) {
|
|
369
|
+
readable = false;
|
|
370
|
+
break;
|
|
371
|
+
}
|
|
372
|
+
const batch = (body?.jobs ?? []);
|
|
373
|
+
for (const j of batch) {
|
|
374
|
+
list.push({
|
|
375
|
+
id: j.id, name: String(j.name ?? ""), conclusion: j.conclusion ?? null, startedAt: j.started_at ?? null, completedAt: j.completed_at ?? null,
|
|
376
|
+
failedSteps: (j.steps ?? []).filter((s) => s.conclusion === "failure").map((s) => String(s.name ?? "")),
|
|
377
|
+
});
|
|
378
|
+
}
|
|
379
|
+
if (batch.length < 100)
|
|
380
|
+
break;
|
|
381
|
+
}
|
|
382
|
+
if (readable)
|
|
383
|
+
jobs.set(run.id, list);
|
|
384
|
+
}
|
|
385
|
+
const checkJobs = red.flatMap((run) => (jobs.get(run.id) ?? []).filter((j) => (j.conclusion === "failure" || j.conclusion === "timed_out") && bucketJob(j, patterns) === "check"));
|
|
386
|
+
log(`Reading failure annotations of ${checkJobs.length} failing check jobs...`);
|
|
387
|
+
for (const job of checkJobs) {
|
|
388
|
+
const { status, body } = await get(`repos/${repository}/check-runs/${job.id}/annotations?per_page=50`);
|
|
389
|
+
if (status !== 200 || !Array.isArray(body))
|
|
390
|
+
continue;
|
|
391
|
+
annotations.set(job.id, body.map((a) => ({ path: a.path ?? null, title: a.title ?? null, message: a.message ?? null, level: a.annotation_level ?? null })));
|
|
392
|
+
}
|
|
393
|
+
}
|
|
394
|
+
catch (error) {
|
|
395
|
+
if (!(error instanceof StopCollection))
|
|
396
|
+
throw error;
|
|
397
|
+
stoppedEarly = error.message;
|
|
398
|
+
}
|
|
399
|
+
const rows = classify({ repository, runs, jobs, annotations, patterns });
|
|
400
|
+
if (!stoppedEarly) {
|
|
401
|
+
const byId = new Map(runs.map((r) => [r.id, r]));
|
|
402
|
+
const preventable = rows.filter((r) => r.verdict === "preventable");
|
|
403
|
+
if (preventable.length)
|
|
404
|
+
log(`Checking ${preventable.length} preventable head commits for coding-agent co-authors...`);
|
|
405
|
+
try {
|
|
406
|
+
for (const row of preventable) {
|
|
407
|
+
const run = byId.get(row.run);
|
|
408
|
+
const { status, body } = await get(`repos/${repository}/commits/${run.headSha}`);
|
|
409
|
+
const message = status === 200 ? String(body?.commit?.message ?? "") : "";
|
|
410
|
+
row.agent = { ...agentMarker(message, run.headBranch), commitRead: status === 200 };
|
|
411
|
+
}
|
|
412
|
+
}
|
|
413
|
+
catch (error) {
|
|
414
|
+
if (!(error instanceof StopCollection))
|
|
415
|
+
throw error;
|
|
416
|
+
stoppedEarly = error.message;
|
|
417
|
+
}
|
|
418
|
+
}
|
|
419
|
+
const report = summarise(repository, runs, rows, stoppedEarly);
|
|
420
|
+
report.workflow = workflowLabel || runs[0]?.workflowName || null;
|
|
421
|
+
return report;
|
|
422
|
+
}
|
|
423
|
+
export function resolveGitHubToken(env) {
|
|
424
|
+
const fromEnv = env.GITHUB_TOKEN || env.GH_TOKEN;
|
|
425
|
+
if (fromEnv)
|
|
426
|
+
return fromEnv;
|
|
427
|
+
const gh = spawnSync("gh", ["auth", "token"], { encoding: "utf8" });
|
|
428
|
+
const token = gh.status === 0 ? gh.stdout.trim() : "";
|
|
429
|
+
return token || undefined;
|
|
430
|
+
}
|
|
431
|
+
export const RED_BUILDS_USAGE = `Usage: diffci red-builds <owner/repo> [--runs <n>] [--workflow <id|file>] [--json <file>]
|
|
432
|
+
[--check-jobs <regex>] [--ci-only-jobs <regex>]
|
|
433
|
+
How many of a repository's red pull request builds failed on checks the author could have run before
|
|
434
|
+
pushing. Reads GitHub Actions history (read-only, paced) and runs nothing. Needs a GitHub token:
|
|
435
|
+
GITHUB_TOKEN, GH_TOKEN, or a signed-in gh CLI. --runs: most recent pull request runs to read (default 200,
|
|
436
|
+
max 1000). --check-jobs / --ci-only-jobs: regexes that override which job names count as local checks.`;
|
|
437
|
+
/** Entry point for `diffci red-builds`. Returns the exit code: 0 on a report, 2 on bad input or errors. */
|
|
438
|
+
export async function runRedBuildsCommand(args, env = process.env, deps = {}) {
|
|
439
|
+
let repository;
|
|
440
|
+
const flags = {};
|
|
441
|
+
for (let i = 0; i < args.length; i++) {
|
|
442
|
+
const arg = args[i];
|
|
443
|
+
if (arg === "--help" || arg === "-h") {
|
|
444
|
+
console.log(RED_BUILDS_USAGE);
|
|
445
|
+
return 0;
|
|
446
|
+
}
|
|
447
|
+
if (arg.startsWith("--")) {
|
|
448
|
+
const [name, inline] = arg.slice(2).split(/=(.*)/s, 2);
|
|
449
|
+
if (!["runs", "workflow", "json", "check-jobs", "ci-only-jobs"].includes(name)) {
|
|
450
|
+
console.error(`Unsupported red-builds argument: --${name}\n\n${RED_BUILDS_USAGE}`);
|
|
451
|
+
return 2;
|
|
452
|
+
}
|
|
453
|
+
const value = inline ?? args[++i];
|
|
454
|
+
if (value === undefined) {
|
|
455
|
+
console.error(`--${name} needs a value`);
|
|
456
|
+
return 2;
|
|
457
|
+
}
|
|
458
|
+
flags[name] = value;
|
|
459
|
+
}
|
|
460
|
+
else if (!repository)
|
|
461
|
+
repository = arg;
|
|
462
|
+
else {
|
|
463
|
+
console.error(`Unexpected argument: ${arg}\n\n${RED_BUILDS_USAGE}`);
|
|
464
|
+
return 2;
|
|
465
|
+
}
|
|
466
|
+
}
|
|
467
|
+
if (!repository || !REPOSITORY.test(repository)) {
|
|
468
|
+
console.error(`red-builds needs a repository as owner/name.\n\n${RED_BUILDS_USAGE}`);
|
|
469
|
+
return 2;
|
|
470
|
+
}
|
|
471
|
+
const maxRuns = flags.runs === undefined ? 200 : Number(flags.runs);
|
|
472
|
+
if (!Number.isInteger(maxRuns) || maxRuns < 1 || maxRuns > 1000) {
|
|
473
|
+
console.error("--runs must be a whole number from 1 to 1000");
|
|
474
|
+
return 2;
|
|
475
|
+
}
|
|
476
|
+
let patterns;
|
|
477
|
+
try {
|
|
478
|
+
patterns = {
|
|
479
|
+
checkJob: flags["check-jobs"] ? new RegExp(flags["check-jobs"], "i") : CHECK_JOB,
|
|
480
|
+
ciOnlyJob: flags["ci-only-jobs"] ? new RegExp(flags["ci-only-jobs"], "i") : CI_ONLY_JOB,
|
|
481
|
+
};
|
|
482
|
+
}
|
|
483
|
+
catch (error) {
|
|
484
|
+
console.error(`Invalid job regex: ${error instanceof Error ? error.message : String(error)}`);
|
|
485
|
+
return 2;
|
|
486
|
+
}
|
|
487
|
+
let get = deps.get;
|
|
488
|
+
if (!get) {
|
|
489
|
+
const token = resolveGitHubToken(env);
|
|
490
|
+
if (!token) {
|
|
491
|
+
console.error("red-builds needs a GitHub token: set GITHUB_TOKEN or GH_TOKEN, or sign in with `gh auth login`. Unauthenticated access allows only 60 calls an hour.");
|
|
492
|
+
return 2;
|
|
493
|
+
}
|
|
494
|
+
get = githubClient(token);
|
|
495
|
+
}
|
|
496
|
+
try {
|
|
497
|
+
const report = await collectRedBuilds({ repository, get, maxRuns, workflow: flags.workflow, patterns, log: (line) => console.error(line) });
|
|
498
|
+
console.log(formatReport(report));
|
|
499
|
+
if (flags.json)
|
|
500
|
+
writeFileSync(flags.json, `${JSON.stringify(report, null, 2)}\n`);
|
|
501
|
+
return 0;
|
|
502
|
+
}
|
|
503
|
+
catch (error) {
|
|
504
|
+
console.error(`DiffCI red-builds failed: ${error instanceof Error ? error.message : String(error)}`);
|
|
505
|
+
return 2;
|
|
506
|
+
}
|
|
507
|
+
}
|
|
@@ -111,14 +111,31 @@ function runInvokesDiffCiVerification(run) {
|
|
|
111
111
|
* `./packages/diffci-cli/package.json`, and `check` reported both of those jobs as badly installed
|
|
112
112
|
* observers. An echo line with a substitution, pipe or command separator is kept, because it can run
|
|
113
113
|
* something.
|
|
114
|
+
*
|
|
115
|
+
* Three more (2026-11-13), all from Core's own release workflow, which `check` on Core reported as
|
|
116
|
+
* seven BLOCKING findings in jobs that publish DiffCI rather than run it:
|
|
117
|
+
* - scp-style Git remotes (`git@gitlab.com:diffci/diffci.git`), which are addresses like URLs;
|
|
118
|
+
* - plain `git` lines (`git commit -m "DiffCI components …"`, `git config user.name "DiffCI release"`),
|
|
119
|
+
* whose arguments are names, messages and refs. As with echo, a line with a substitution, pipe or
|
|
120
|
+
* command separator is kept;
|
|
121
|
+
* - the package spec of `npm view`/`info`/`show`, which reads registry metadata and never runs the
|
|
122
|
+
* package. `version=$(npm view @diffci.com/diffci@latest version)` resolves a version to pin.
|
|
114
123
|
*/
|
|
115
124
|
function commandText(run) {
|
|
116
125
|
return run
|
|
117
126
|
.split("\n")
|
|
118
|
-
.map((line) => line.replace(/(^|\s)#.*$/, "$1").replace(/[a-z][a-z0-9+.-]*:\/\/\S+/gi, " "))
|
|
119
|
-
.map((line) => (/^\s*(?:echo|printf)\s/.test(line) && !/\$\(|`|\||&&|;/.test(line) ? "" : line))
|
|
120
127
|
.map((line) => line
|
|
121
|
-
.replace(/(^|\s)
|
|
128
|
+
.replace(/(^|\s)#.*$/, "$1")
|
|
129
|
+
.replace(/[a-z][a-z0-9+.-]*:\/\/\S+/gi, " ")
|
|
130
|
+
.replace(/\b[\w.-]+@[\w-]+(?:\.[\w-]+)+:[^\s"']+/g, " ")
|
|
131
|
+
.replace(/\bnpm(?:\.cmd)?\s+(?:view|info|show)\s+["']?[^\s"')]+["']?/g, "npm view "))
|
|
132
|
+
// Separators inside quotes are message text ("…/diffci; enable its write access"), so only
|
|
133
|
+
// unquoted ones count. A substitution counts anywhere, because double quotes still run it.
|
|
134
|
+
.map((line) => (/^\s*(?:echo|printf|git)\s/.test(line) && !/\$\(|`/.test(line) &&
|
|
135
|
+
!/\||&&|;/.test(line.replace(/"[^"]*"|'[^']*'/g, "")) ? "" : line))
|
|
136
|
+
.map((line) => line
|
|
137
|
+
// A field value may be quoted from its middle: `-f message="Release DiffCI …"`.
|
|
138
|
+
.replace(/(^|\s)(?:-[fF]|--(?:raw-)?field)\s+(?:(?:[^\s"']*(?:"[^"]*"|'[^']*'))+[^\s"']*|\S+)/g, "$1")
|
|
122
139
|
.replace(/(^|[\s"'])repos\/[^\s"']+/g, "$1")
|
|
123
140
|
.replace(/\$?\{?\b[A-Z][A-Z0-9]*_[A-Z0-9_]+\b\}?/g, " ")
|
|
124
141
|
.replace(/[^\s"'()]*\.json\b/g, " "))
|
|
@@ -165,6 +182,12 @@ function referencesDiffCi(uses, repoPath, actionPattern) {
|
|
|
165
182
|
}
|
|
166
183
|
return false;
|
|
167
184
|
}
|
|
185
|
+
/** Action inputs that deliberately let the DiffCI step decide its own job's outcome. */
|
|
186
|
+
const ACTION_GATE_INPUTS = ["verify", "check-run", "fail-on-error"];
|
|
187
|
+
function actionGateInputs(step) {
|
|
188
|
+
const inputs = isRecord(step.with) ? step.with : {};
|
|
189
|
+
return ACTION_GATE_INPUTS.filter((name) => inputs[name] === true || String(inputs[name]).trim().toLowerCase() === "true");
|
|
190
|
+
}
|
|
168
191
|
function isPinnedToSha(uses) {
|
|
169
192
|
const at = uses.lastIndexOf("@");
|
|
170
193
|
if (at === -1)
|
|
@@ -201,9 +224,24 @@ export function auditWorkflows(repoPath, options = {}) {
|
|
|
201
224
|
const steps = asArray(rawJob.steps).filter(isRecord);
|
|
202
225
|
const isDiffCiStep = (step) => (typeof step.uses === "string" && referencesDiffCi(step.uses, repoPath, actionPattern)) ||
|
|
203
226
|
(typeof step.run === "string" && runReferencesDiffCi(step.run, actionPattern));
|
|
204
|
-
const isVerificationStep = (step) => typeof step.run === "string" && runInvokesDiffCiVerification(step.run)
|
|
227
|
+
const isVerificationStep = (step) => (typeof step.run === "string" && runInvokesDiffCiVerification(step.run)) ||
|
|
228
|
+
(typeof step.uses === "string" && isDiffCiStep(step) && actionGateInputs(step).length > 0);
|
|
205
229
|
// This guard proves that observation jobs are inert. A dedicated fail-closed verification job
|
|
206
230
|
// is a different product surface: making its own status check fail is its intended contract.
|
|
231
|
+
// The Action reaches the same surface through inputs: `verify` (the fast check), `check-run`
|
|
232
|
+
// (the merge gate) and `fail-on-error`. Before 2026-11-13 only the `run:` form was recognised,
|
|
233
|
+
// so every repository that turned on the 0.3.41 merge gate was told its installation was broken.
|
|
234
|
+
for (const step of steps) {
|
|
235
|
+
if (typeof step.uses === "string" && isDiffCiStep(step) && actionGateInputs(step).includes("fail-on-error")) {
|
|
236
|
+
findings.push({
|
|
237
|
+
severity: "WARNING",
|
|
238
|
+
code: "ACTION_FAILS_ON_ERROR",
|
|
239
|
+
message: `job "${jobId}" sets fail-on-error: "true", so a DiffCI refusal or error fails this job. That is meant for debugging an installation or testing the Action; turn it off for observation.`,
|
|
240
|
+
workflow: relativePath,
|
|
241
|
+
job: jobId,
|
|
242
|
+
});
|
|
243
|
+
}
|
|
244
|
+
}
|
|
207
245
|
const diffciSteps = steps.filter((step) => isDiffCiStep(step) && !isVerificationStep(step));
|
|
208
246
|
if (diffciSteps.length === 0)
|
|
209
247
|
continue;
|