@diffci.com/diffci 0.3.39 → 0.3.41

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";
@@ -1412,6 +1414,7 @@ Usage:
1412
1414
  [--redact-paths] [--json] [--quiet] [--fail-on-error] [--timeout-ms <ms>] [--share-usage]
1413
1415
  diffci plan --base <sha> [--head <sha>] [--repo <path>]
1414
1416
  diffci check-plan --plan <plan.json> --results <junit.xml>
1417
+ diffci red-builds <owner/repo> [--runs <n>] [--workflow <id|file>] [--json <file>]
1415
1418
  diffci pilot --full <command> [--selected <command>] [--repo <path>] [--out-dir <dir>] [--label <name>]
1416
1419
  diffci pilot-packet [--repo <path>] [--out-dir <dir>] [--base <sha> --head <sha>]
1417
1420
  [--label <name>] [--repository-url <https-url>] [--redact-paths]
@@ -1533,6 +1536,11 @@ async function main() {
1533
1536
  process.exitCode = await runPlanCommand(process.argv.slice(3));
1534
1537
  return;
1535
1538
  }
1539
+ // Stateless and read-only like check-plan: no shared flags, telemetry or feedback prompt.
1540
+ if (process.argv[2] === "red-builds") {
1541
+ process.exitCode = await runRedBuildsCommand(process.argv.slice(3));
1542
+ return;
1543
+ }
1536
1544
  const { command, flags } = parseArgs(process.argv);
1537
1545
  const env = process.env;
1538
1546
  if (flags.help === true || command === "help" || command === undefined) {
@@ -0,0 +1,123 @@
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
+ export interface CollectOptions {
109
+ repository: string;
110
+ get: GitHubGet;
111
+ maxRuns: number;
112
+ workflow?: string;
113
+ patterns?: Patterns;
114
+ log?: (line: string) => void;
115
+ }
116
+ /** Fetches runs, jobs, annotations and commit messages, then classifies. Partial data on a stop. */
117
+ export declare function collectRedBuilds(options: CollectOptions): Promise<RedBuildsReport>;
118
+ export declare function resolveGitHubToken(env: NodeJS.ProcessEnv): string | undefined;
119
+ 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.";
120
+ /** Entry point for `diffci red-builds`. Returns the exit code: 0 on a report, 2 on bad input or errors. */
121
+ export declare function runRedBuildsCommand(args: string[], env?: NodeJS.ProcessEnv, deps?: {
122
+ get?: GitHubGet;
123
+ }): Promise<number>;
@@ -0,0 +1,477 @@
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 res = await 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
+ if (res.headers.get("retry-after"))
267
+ throw new StopCollection(`GitHub asked to slow down (Retry-After on ${path.split("?")[0]})`);
268
+ const remaining = Number(res.headers.get("x-ratelimit-remaining") ?? "Infinity");
269
+ const body = res.status === 204 ? undefined : await res.json().catch(() => undefined);
270
+ if (res.status === 401)
271
+ throw new Error("GitHub rejected the token (401)");
272
+ if (res.status === 403 && remaining === 0)
273
+ throw new StopCollection("the hourly GitHub API quota is used up");
274
+ if (remaining < floor)
275
+ throw new StopCollection(`fewer than ${floor} GitHub API calls left this hour`);
276
+ return { status: res.status, body };
277
+ };
278
+ }
279
+ /** Fetches runs, jobs, annotations and commit messages, then classifies. Partial data on a stop. */
280
+ export async function collectRedBuilds(options) {
281
+ const { repository, get } = options;
282
+ const log = options.log ?? (() => undefined);
283
+ const patterns = options.patterns ?? DEFAULT_PATTERNS;
284
+ const runs = [];
285
+ const jobs = new Map();
286
+ const annotations = new Map();
287
+ let stoppedEarly = null;
288
+ let workflow = options.workflow;
289
+ let workflowLabel = workflow ?? "";
290
+ try {
291
+ if (!workflow) {
292
+ // Default: the heaviest pull request workflow (most wall-clock time in one sample page), which is the
293
+ // main CI in practice. Counting runs of every workflow lets labelers and bots flood the window.
294
+ const { status, body } = await get(`repos/${repository}/actions/runs?event=pull_request&per_page=100`);
295
+ if (status === 404)
296
+ throw new Error(`${repository} not found, or its Actions history is not visible to this token`);
297
+ if (status !== 200)
298
+ throw new Error(`listing workflow runs failed (HTTP ${status})`);
299
+ const weight = new Map();
300
+ for (const r of body?.workflow_runs ?? []) {
301
+ const span = (Date.parse(r.updated_at) - Date.parse(r.run_started_at ?? r.created_at)) / 60_000;
302
+ const entry = weight.get(r.workflow_id) ?? { name: String(r.name ?? r.workflow_id), minutes: 0 };
303
+ entry.minutes += Number.isFinite(span) && span > 0 ? span : 0;
304
+ weight.set(r.workflow_id, entry);
305
+ }
306
+ const heaviest = [...weight.entries()].sort((a, b) => b[1].minutes - a[1].minutes)[0];
307
+ if (!heaviest)
308
+ return summarise(repository, [], [], null);
309
+ workflow = String(heaviest[0]);
310
+ workflowLabel = heaviest[1].name;
311
+ log(`Using the "${workflowLabel}" workflow, the heaviest one run on pull requests. Pass --workflow to choose another.`);
312
+ }
313
+ const base = `repos/${repository}/actions/workflows/${encodeURIComponent(workflow)}/runs`;
314
+ for (let page = 1; runs.length < options.maxRuns; page++) {
315
+ const { status, body } = await get(`${base}?event=pull_request&per_page=100&page=${page}`);
316
+ if (status === 404)
317
+ throw new Error(`${repository} workflow ${workflow} not found, or its Actions history is not visible to this token`);
318
+ if (status !== 200)
319
+ throw new Error(`listing workflow runs failed (HTTP ${status})`);
320
+ const batch = (body?.workflow_runs ?? []);
321
+ for (const r of batch.slice(0, options.maxRuns - runs.length)) {
322
+ runs.push({
323
+ id: r.id, workflowId: r.workflow_id, workflowName: String(r.name ?? ""), attempt: r.run_attempt ?? 1,
324
+ headSha: r.head_sha, headBranch: String(r.head_branch ?? ""), headRepo: String(r.head_repository?.full_name ?? ""),
325
+ conclusion: r.conclusion ?? null, createdAt: r.created_at,
326
+ });
327
+ }
328
+ if (batch.length < 100)
329
+ break;
330
+ }
331
+ const red = runs.filter((r) => r.conclusion === "failure");
332
+ log(`${runs.length} pull request runs, ${red.length} red. Reading their jobs...`);
333
+ for (const run of red) {
334
+ const list = [];
335
+ let readable = true;
336
+ for (let page = 1;; page++) {
337
+ const { status, body } = await get(`repos/${repository}/actions/runs/${run.id}/attempts/${run.attempt}/jobs?per_page=100&page=${page}`);
338
+ if (status !== 200) {
339
+ readable = false;
340
+ break;
341
+ }
342
+ const batch = (body?.jobs ?? []);
343
+ for (const j of batch) {
344
+ list.push({
345
+ id: j.id, name: String(j.name ?? ""), conclusion: j.conclusion ?? null, startedAt: j.started_at ?? null, completedAt: j.completed_at ?? null,
346
+ failedSteps: (j.steps ?? []).filter((s) => s.conclusion === "failure").map((s) => String(s.name ?? "")),
347
+ });
348
+ }
349
+ if (batch.length < 100)
350
+ break;
351
+ }
352
+ if (readable)
353
+ jobs.set(run.id, list);
354
+ }
355
+ const checkJobs = red.flatMap((run) => (jobs.get(run.id) ?? []).filter((j) => (j.conclusion === "failure" || j.conclusion === "timed_out") && bucketJob(j, patterns) === "check"));
356
+ log(`Reading failure annotations of ${checkJobs.length} failing check jobs...`);
357
+ for (const job of checkJobs) {
358
+ const { status, body } = await get(`repos/${repository}/check-runs/${job.id}/annotations?per_page=50`);
359
+ if (status !== 200 || !Array.isArray(body))
360
+ continue;
361
+ annotations.set(job.id, body.map((a) => ({ path: a.path ?? null, title: a.title ?? null, message: a.message ?? null, level: a.annotation_level ?? null })));
362
+ }
363
+ }
364
+ catch (error) {
365
+ if (!(error instanceof StopCollection))
366
+ throw error;
367
+ stoppedEarly = error.message;
368
+ }
369
+ const rows = classify({ repository, runs, jobs, annotations, patterns });
370
+ if (!stoppedEarly) {
371
+ const byId = new Map(runs.map((r) => [r.id, r]));
372
+ const preventable = rows.filter((r) => r.verdict === "preventable");
373
+ if (preventable.length)
374
+ log(`Checking ${preventable.length} preventable head commits for coding-agent co-authors...`);
375
+ try {
376
+ for (const row of preventable) {
377
+ const run = byId.get(row.run);
378
+ const { status, body } = await get(`repos/${repository}/commits/${run.headSha}`);
379
+ const message = status === 200 ? String(body?.commit?.message ?? "") : "";
380
+ row.agent = { ...agentMarker(message, run.headBranch), commitRead: status === 200 };
381
+ }
382
+ }
383
+ catch (error) {
384
+ if (!(error instanceof StopCollection))
385
+ throw error;
386
+ stoppedEarly = error.message;
387
+ }
388
+ }
389
+ const report = summarise(repository, runs, rows, stoppedEarly);
390
+ report.workflow = workflowLabel || runs[0]?.workflowName || null;
391
+ return report;
392
+ }
393
+ export function resolveGitHubToken(env) {
394
+ const fromEnv = env.GITHUB_TOKEN || env.GH_TOKEN;
395
+ if (fromEnv)
396
+ return fromEnv;
397
+ const gh = spawnSync("gh", ["auth", "token"], { encoding: "utf8" });
398
+ const token = gh.status === 0 ? gh.stdout.trim() : "";
399
+ return token || undefined;
400
+ }
401
+ export const RED_BUILDS_USAGE = `Usage: diffci red-builds <owner/repo> [--runs <n>] [--workflow <id|file>] [--json <file>]
402
+ [--check-jobs <regex>] [--ci-only-jobs <regex>]
403
+ How many of a repository's red pull request builds failed on checks the author could have run before
404
+ pushing. Reads GitHub Actions history (read-only, paced) and runs nothing. Needs a GitHub token:
405
+ GITHUB_TOKEN, GH_TOKEN, or a signed-in gh CLI. --runs: most recent pull request runs to read (default 200,
406
+ max 1000). --check-jobs / --ci-only-jobs: regexes that override which job names count as local checks.`;
407
+ /** Entry point for `diffci red-builds`. Returns the exit code: 0 on a report, 2 on bad input or errors. */
408
+ export async function runRedBuildsCommand(args, env = process.env, deps = {}) {
409
+ let repository;
410
+ const flags = {};
411
+ for (let i = 0; i < args.length; i++) {
412
+ const arg = args[i];
413
+ if (arg === "--help" || arg === "-h") {
414
+ console.log(RED_BUILDS_USAGE);
415
+ return 0;
416
+ }
417
+ if (arg.startsWith("--")) {
418
+ const [name, inline] = arg.slice(2).split(/=(.*)/s, 2);
419
+ if (!["runs", "workflow", "json", "check-jobs", "ci-only-jobs"].includes(name)) {
420
+ console.error(`Unsupported red-builds argument: --${name}\n\n${RED_BUILDS_USAGE}`);
421
+ return 2;
422
+ }
423
+ const value = inline ?? args[++i];
424
+ if (value === undefined) {
425
+ console.error(`--${name} needs a value`);
426
+ return 2;
427
+ }
428
+ flags[name] = value;
429
+ }
430
+ else if (!repository)
431
+ repository = arg;
432
+ else {
433
+ console.error(`Unexpected argument: ${arg}\n\n${RED_BUILDS_USAGE}`);
434
+ return 2;
435
+ }
436
+ }
437
+ if (!repository || !REPOSITORY.test(repository)) {
438
+ console.error(`red-builds needs a repository as owner/name.\n\n${RED_BUILDS_USAGE}`);
439
+ return 2;
440
+ }
441
+ const maxRuns = flags.runs === undefined ? 200 : Number(flags.runs);
442
+ if (!Number.isInteger(maxRuns) || maxRuns < 1 || maxRuns > 1000) {
443
+ console.error("--runs must be a whole number from 1 to 1000");
444
+ return 2;
445
+ }
446
+ let patterns;
447
+ try {
448
+ patterns = {
449
+ checkJob: flags["check-jobs"] ? new RegExp(flags["check-jobs"], "i") : CHECK_JOB,
450
+ ciOnlyJob: flags["ci-only-jobs"] ? new RegExp(flags["ci-only-jobs"], "i") : CI_ONLY_JOB,
451
+ };
452
+ }
453
+ catch (error) {
454
+ console.error(`Invalid job regex: ${error instanceof Error ? error.message : String(error)}`);
455
+ return 2;
456
+ }
457
+ let get = deps.get;
458
+ if (!get) {
459
+ const token = resolveGitHubToken(env);
460
+ if (!token) {
461
+ 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.");
462
+ return 2;
463
+ }
464
+ get = githubClient(token);
465
+ }
466
+ try {
467
+ const report = await collectRedBuilds({ repository, get, maxRuns, workflow: flags.workflow, patterns, log: (line) => console.error(line) });
468
+ console.log(formatReport(report));
469
+ if (flags.json)
470
+ writeFileSync(flags.json, `${JSON.stringify(report, null, 2)}\n`);
471
+ return 0;
472
+ }
473
+ catch (error) {
474
+ console.error(`DiffCI red-builds failed: ${error instanceof Error ? error.message : String(error)}`);
475
+ return 2;
476
+ }
477
+ }
@@ -19,7 +19,7 @@ If DiffCI saves you CI time, a ⭐ helps others find it.
19
19
 
20
20
  ```yaml
21
21
  - uses: actions/checkout@v7
22
- - uses: DiffCI/core@v0.3.38
22
+ - uses: DiffCI/core@v0.3.39
23
23
  ```
24
24
 
25
25
  Add `with: comment: "true"` (and `pull-requests: write` on the job) and the same answer appears on the pull request itself, updated in place on each push:
@@ -75,6 +75,8 @@ export declare function exportsRemapTargets(oldContent: string | undefined, newC
75
75
  } | undefined;
76
76
  /** packageJsonChange's kind, with a dependency change reported as behavioral. */
77
77
  export declare function packageJsonChangeKind(oldContent: string | undefined, newContent: string | undefined): "metadata" | "data" | "behavioral";
78
+ /** Exported for tests only: a test-runner or transform configuration below the repository root. */
79
+ export declare function isNestedTestConfig(path: string): boolean;
78
80
  /** `isCiConfig` defaults to names alone; analyzeGitDelta also passes what GitLab `include` reaches. */
79
81
  export declare function computeAnalysis(files: ChangedFile[], isCiConfig?: (path: string) => boolean): GitDeltaAnalysis;
80
82
  export declare function summarize(files: ChangedFile[]): GitDeltaSummary;