@diffci.com/diffci 0.3.44 → 0.3.46

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.
@@ -1,4 +1,8 @@
1
- export declare const RED_BUILDS_SCHEMA = 1;
1
+ /**
2
+ * 2 (2026-11-16): rows carry `branchAgent`, the report adds `byBranchAgent`, and an agent
3
+ * found by its branch prefix is named (`"copilot"`) with `source: "branch"` instead of `"branch prefix"`.
4
+ */
5
+ export declare const RED_BUILDS_SCHEMA = 2;
2
6
  export type JobBucket = "infra" | "ci-only" | "check";
3
7
  export type Verdict = "preventable" | "partly" | "likely" | "shared" | "ci-only" | "flaky" | "infra";
4
8
  export declare const VERDICTS: readonly Verdict[];
@@ -32,7 +36,7 @@ export interface Patterns {
32
36
  ciOnlyJob: RegExp;
33
37
  }
34
38
  export declare const DEFAULT_PATTERNS: Patterns;
35
- export declare function bucketJob(job: JobSummary, patterns?: Patterns): JobBucket;
39
+ export declare function bucketJob(job: JobSummary, patterns?: Patterns, workflowName?: string): JobBucket;
36
40
  export declare function isAggregateJob(job: JobSummary): boolean;
37
41
  /** Failure signatures of one job: annotation path, title and first message line, with volatile parts blurred. */
38
42
  export declare function signatures(annotations: Annotation[]): Set<string>;
@@ -51,9 +55,16 @@ export interface RedRun {
51
55
  ownership?: "own" | "shared" | "timeout" | "unknown";
52
56
  }>;
53
57
  runnerMinutes: number;
58
+ /**
59
+ * The coding agent the head branch is named after (`copilot/fix-123` -> "copilot"), or null. Free: no API
60
+ * call. The branch name itself is left out, since names such as `jane/fix` can carry a user name.
61
+ */
62
+ branchAgent: string | null;
63
+ /** Preventable runs only: agent co-author trailer or branch prefix, after reading the head commit. */
54
64
  agent?: {
55
65
  written: boolean;
56
66
  marker: string;
67
+ source: "trailer" | "branch" | "";
57
68
  commitRead: boolean;
58
69
  };
59
70
  }
@@ -68,10 +79,23 @@ export interface ClassifyInput {
68
79
  }
69
80
  /** Pure: sorts every red run whose jobs were read into one verdict. */
70
81
  export declare function classify(input: ClassifyInput): RedRun[];
82
+ /** The coding agent a branch is named after: `copilot/fix-123` and `claude-fix` give "copilot" and "claude". */
83
+ export declare function branchAgent(branch: string): string | null;
71
84
  export declare function agentMarker(message: string, branch: string): {
72
85
  written: boolean;
73
86
  marker: string;
87
+ source: "trailer" | "branch" | "";
74
88
  };
89
+ /** Pull request runs and red-run verdicts for one group of branches. */
90
+ export interface BranchAgentSlice {
91
+ pullRequestRuns: number;
92
+ redRuns: number;
93
+ analysed: number;
94
+ verdicts: Record<Verdict, number>;
95
+ preventableRunnerMinutes: number;
96
+ }
97
+ /** Key in `byBranchAgent` for runs whose branch names no coding agent. */
98
+ export declare const NO_AGENT_BRANCH = "other";
75
99
  export interface RedBuildsReport {
76
100
  schemaVersion: typeof RED_BUILDS_SCHEMA;
77
101
  repository: string;
@@ -93,10 +117,16 @@ export interface RedBuildsReport {
93
117
  runnerMinutes: number;
94
118
  }>;
95
119
  agentWrittenPreventable: number;
120
+ /**
121
+ * The same counts split by the coding agent each run's head branch is named after (`copilot`, `claude`...),
122
+ * with every other branch under `other`. Branch prefixes undercount agents that use ordinary branch names.
123
+ */
124
+ byBranchAgent: Record<string, BranchAgentSlice>;
96
125
  stoppedEarly: string | null;
97
126
  rows: RedRun[];
98
127
  }
99
- export declare function summarise(repository: string, runs: RunSummary[], rows: RedRun[], stoppedEarly: string | null, neverStarted?: number): RedBuildsReport;
128
+ /** `neverStarted`: the runs marked failed although no job started, as ids (for the per-agent split) or a count. */
129
+ export declare function summarise(repository: string, runs: RunSummary[], rows: RedRun[], stoppedEarly: string | null, neverStarted?: number | ReadonlySet<number>): RedBuildsReport;
100
130
  export declare function formatReport(report: RedBuildsReport): string;
101
131
  export type GitHubGet = (path: string) => Promise<{
102
132
  status: number;
@@ -120,7 +150,10 @@ export declare function pickMainWorkflow(sample: any[]): {
120
150
  id: number;
121
151
  name: string;
122
152
  path: string;
153
+ confident: boolean;
123
154
  } | undefined;
155
+ /** Likely main CI workflows from the repository's workflow list, best first, for a --workflow suggestion. */
156
+ export declare function suggestWorkflows(workflows: any[]): string[];
124
157
  export interface CollectOptions {
125
158
  repository: string;
126
159
  get: GitHubGet;
@@ -132,7 +165,7 @@ export interface CollectOptions {
132
165
  /** Fetches runs, jobs, annotations and commit messages, then classifies. Partial data on a stop. */
133
166
  export declare function collectRedBuilds(options: CollectOptions): Promise<RedBuildsReport>;
134
167
  export declare function resolveGitHubToken(env: NodeJS.ProcessEnv): string | undefined;
135
- 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.";
168
+ 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.\nRuns on branches named after a coding agent (copilot/, claude/, codex/...) are also counted per agent.";
136
169
  /** Entry point for `diffci red-builds`. Returns the exit code: 0 on a report, 2 on bad input or errors. */
137
170
  export declare function runRedBuildsCommand(args: string[], env?: NodeJS.ProcessEnv, deps?: {
138
171
  get?: GitHubGet;
@@ -24,7 +24,11 @@
24
24
  */
25
25
  import { spawnSync } from "node:child_process";
26
26
  import { writeFileSync } from "node:fs";
27
- export const RED_BUILDS_SCHEMA = 1;
27
+ /**
28
+ * 2 (2026-11-16): rows carry `branchAgent`, the report adds `byBranchAgent`, and an agent
29
+ * found by its branch prefix is named (`"copilot"`) with `source: "branch"` instead of `"branch prefix"`.
30
+ */
31
+ export const RED_BUILDS_SCHEMA = 2;
28
32
  const REPOSITORY = /^[A-Za-z0-9][A-Za-z0-9-]{0,38}\/[A-Za-z0-9._-]{1,100}$/;
29
33
  const INFRA_STEP = /set up|setup|checkout|install|cache|download|upload|restore|docker|login|post /i;
30
34
  /** Jobs no local check can stand in for, whatever else the name says ("e2e tests" is not a unit test). */
@@ -35,6 +39,11 @@ const CHECK_JOB = /\b(lint(ing)?|eslint|biome|prettier|format(ting)?|fmt|style|t
35
39
  /** Aggregate gate jobs ("all required jobs passed"): they fail because another job did, so they are ignored
36
40
  * whenever another job in the same run failed too. */
37
41
  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;
42
+ /** Gate jobs named after what they check: "Unit Tests - Status Check", "require-all-checks-to-pass". */
43
+ const AGGREGATE_SUFFIX = /(^|\s-\s|\s)(status[- ]checks?|requires?d?[- ]all[- ]checks?([- ]to)?[- ](pass(ed)?|succeed(ed)?))$/i;
44
+ /** Workflows whose every job is a local check, so a job named only by its matrix ("JavaScript (Node.js 24)
45
+ * 1/4") inherits the workflow's kind. Kept narrow: a workflow called "CI" or "Build and Test" says nothing. */
46
+ const LOCAL_CHECK_WORKFLOW = /\b(unit[- ]?tests?|lint(ing)?|typecheck|type[- ]?checks?|static[- ]analysis)\b/i;
38
47
  const CI_ONLY_STEP = /lockfile|lock file|migration ordering/i;
39
48
  const GENERIC_ANNOTATION = /process completed with exit code|^command failed|elifecycle|exited with code/i;
40
49
  const TIMEOUT = /timed out|timeout/i;
@@ -42,7 +51,7 @@ const AGENT_TRAILER = /co-authored-by:[^\n]*?\b(claude|cursor|copilot|codex|devi
42
51
  const AGENT_BRANCH = /^(claude|codex|copilot|cursor|devin|jules)[/-]/i;
43
52
  export const VERDICTS = ["preventable", "partly", "likely", "shared", "ci-only", "flaky", "infra"];
44
53
  export const DEFAULT_PATTERNS = { checkJob: CHECK_JOB, ciOnlyJob: CI_ONLY_JOB };
45
- export function bucketJob(job, patterns = DEFAULT_PATTERNS) {
54
+ export function bucketJob(job, patterns = DEFAULT_PATTERNS, workflowName = "") {
46
55
  if (job.failedSteps.length === 0)
47
56
  return "infra"; // cancelled, timed out or runner lost: no step failed
48
57
  if (job.failedSteps.every((step) => INFRA_STEP.test(step)))
@@ -57,6 +66,8 @@ export function bucketJob(job, patterns = DEFAULT_PATTERNS) {
57
66
  return "ci-only";
58
67
  if (patterns.checkJob.test(name))
59
68
  return "check";
69
+ if (LOCAL_CHECK_WORKFLOW.test(workflowName) && !CI_ONLY_STRONG.test(workflowName) && !patterns.ciOnlyJob.test(name))
70
+ return "check";
60
71
  return "ci-only"; // a CI-side job by name, or one matching neither list: never inflates the preventable count
61
72
  }
62
73
  /** The job's own name, without a "Workflow / " or "caller / " prefix. */
@@ -64,7 +75,8 @@ function jobName(job) {
64
75
  return (job.name.split(" / ").at(-1) ?? job.name).trim();
65
76
  }
66
77
  export function isAggregateJob(job) {
67
- return AGGREGATE_JOB.test(jobName(job).replace(/[()]/g, "").trim());
78
+ const name = jobName(job).replace(/[()]/g, "").trim();
79
+ return AGGREGATE_JOB.test(name) || AGGREGATE_SUFFIX.test(name);
68
80
  }
69
81
  /** Failure signatures of one job: annotation path, title and first message line, with volatile parts blurred. */
70
82
  export function signatures(annotations) {
@@ -98,15 +110,19 @@ export function classify(input) {
98
110
  const passed = new Set(input.runs.filter((r) => r.conclusion === "success").map((r) => `${r.workflowId}:${r.headSha}`));
99
111
  const prKey = (r) => `${r.headRepo}:${r.headBranch}`;
100
112
  const failingOf = (jobs) => jobs.filter((j) => j.conclusion === "failure" || j.conclusion === "timed_out");
101
- // Which PRs each failure signature appeared on, across the whole window.
113
+ // Which PRs each failure signature, and each failing check job, appeared on across the whole window.
102
114
  const seen = new Map();
115
+ const jobFailedOn = new Map();
103
116
  for (const run of input.runs) {
104
117
  const jobs = input.jobs.get(run.id);
105
118
  if (run.conclusion !== "failure" || !jobs)
106
119
  continue;
107
120
  for (const job of failingOf(jobs)) {
108
- if (bucketJob(job, patterns) !== "check")
121
+ if (bucketJob(job, patterns, run.workflowName) !== "check")
109
122
  continue;
123
+ if (!jobFailedOn.has(job.name))
124
+ jobFailedOn.set(job.name, new Set());
125
+ jobFailedOn.get(job.name).add(prKey(run));
110
126
  for (const sig of signatures(input.annotations.get(job.id) ?? [])) {
111
127
  if (!seen.has(sig))
112
128
  seen.set(sig, new Set());
@@ -114,6 +130,13 @@ export function classify(input) {
114
130
  }
115
131
  }
116
132
  }
133
+ // A check job with no annotations that fails on most pull requests is broken for everyone, not for this
134
+ // change (continue's jetbrains-tests failed on all 185 red runs). It counts as shared, never as own.
135
+ const prs = new Set(input.runs.map(prKey)).size;
136
+ const brokenForEveryone = (name) => {
137
+ const failedOn = jobFailedOn.get(name)?.size ?? 0;
138
+ return failedOn >= 5 && failedOn * 2 >= prs;
139
+ };
117
140
  const rows = [];
118
141
  for (const run of input.runs) {
119
142
  const jobs = input.jobs.get(run.id);
@@ -123,14 +146,14 @@ export function classify(input) {
123
146
  // A gate job that only reports "something else failed" says nothing on its own.
124
147
  const failing = allFailing.some((j) => !isAggregateJob(j)) ? allFailing.filter((j) => !isAggregateJob(j)) : allFailing;
125
148
  const detail = failing.map((job) => {
126
- const bucket = bucketJob(job, patterns);
149
+ const bucket = bucketJob(job, patterns, run.workflowName);
127
150
  if (bucket !== "check")
128
151
  return { name: job.name, bucket };
129
152
  const annotations = input.annotations.get(job.id);
130
153
  const sigs = signatures(annotations ?? []);
131
154
  let ownership;
132
155
  if (sigs.size === 0)
133
- ownership = "unknown";
156
+ ownership = brokenForEveryone(job.name) ? "shared" : "unknown";
134
157
  else if ([...sigs].every((s) => TIMEOUT.test(s)))
135
158
  ownership = "timeout";
136
159
  else if ([...sigs].some((s) => !TIMEOUT.test(s) && (seen.get(s)?.size ?? 0) > 1))
@@ -167,19 +190,56 @@ export function classify(input) {
167
190
  verdict,
168
191
  failingJobs: detail,
169
192
  runnerMinutes: Math.round(jobs.reduce((sum, job) => sum + minutes(job), 0) * 10) / 10,
193
+ branchAgent: branchAgent(run.headBranch),
170
194
  });
171
195
  }
172
196
  return rows;
173
197
  }
198
+ /** The coding agent a branch is named after: `copilot/fix-123` and `claude-fix` give "copilot" and "claude". */
199
+ export function branchAgent(branch) {
200
+ return AGENT_BRANCH.exec(branch)?.[1]?.toLowerCase() ?? null;
201
+ }
174
202
  export function agentMarker(message, branch) {
175
203
  const trailer = AGENT_TRAILER.exec(message);
176
204
  if (trailer)
177
- return { written: true, marker: (trailer[1] ?? trailer[2] ?? "agent").toLowerCase() };
178
- if (AGENT_BRANCH.test(branch))
179
- return { written: true, marker: "branch prefix" };
180
- return { written: false, marker: "" };
205
+ return { written: true, marker: (trailer[1] ?? trailer[2] ?? "agent").toLowerCase(), source: "trailer" };
206
+ const fromBranch = branchAgent(branch);
207
+ if (fromBranch)
208
+ return { written: true, marker: fromBranch, source: "branch" };
209
+ return { written: false, marker: "", source: "" };
210
+ }
211
+ /** Key in `byBranchAgent` for runs whose branch names no coding agent. */
212
+ export const NO_AGENT_BRANCH = "other";
213
+ function sliceByBranchAgent(runs, rows, neverStartedIds) {
214
+ const slices = {};
215
+ const sliceOf = (agent) => {
216
+ const key = agent ?? NO_AGENT_BRANCH;
217
+ return slices[key] ??= {
218
+ pullRequestRuns: 0, redRuns: 0, analysed: 0, preventableRunnerMinutes: 0,
219
+ verdicts: Object.fromEntries(VERDICTS.map((v) => [v, 0])),
220
+ };
221
+ };
222
+ for (const run of runs) {
223
+ const slice = sliceOf(branchAgent(run.headBranch));
224
+ slice.pullRequestRuns++;
225
+ if (run.conclusion === "failure" && !neverStartedIds.has(run.id))
226
+ slice.redRuns++;
227
+ }
228
+ for (const row of rows) {
229
+ const slice = sliceOf(row.branchAgent);
230
+ slice.analysed++;
231
+ slice.verdicts[row.verdict]++;
232
+ if (row.verdict === "preventable")
233
+ slice.preventableRunnerMinutes += row.runnerMinutes;
234
+ }
235
+ for (const slice of Object.values(slices))
236
+ slice.preventableRunnerMinutes = Math.round(slice.preventableRunnerMinutes);
237
+ return slices;
181
238
  }
239
+ /** `neverStarted`: the runs marked failed although no job started, as ids (for the per-agent split) or a count. */
182
240
  export function summarise(repository, runs, rows, stoppedEarly, neverStarted = 0) {
241
+ const neverStartedIds = typeof neverStarted === "number" ? new Set() : neverStarted;
242
+ const neverStartedCount = typeof neverStarted === "number" ? neverStarted : neverStarted.size;
183
243
  const verdicts = Object.fromEntries(VERDICTS.map((v) => [v, { runs: 0, runnerMinutes: 0 }]));
184
244
  for (const row of rows) {
185
245
  verdicts[row.verdict].runs++;
@@ -188,7 +248,7 @@ export function summarise(repository, runs, rows, stoppedEarly, neverStarted = 0
188
248
  for (const v of VERDICTS)
189
249
  verdicts[v].runnerMinutes = Math.round(verdicts[v].runnerMinutes);
190
250
  const times = runs.map((r) => r.createdAt).sort();
191
- const red = runs.filter((r) => r.conclusion === "failure").length - neverStarted;
251
+ const red = runs.filter((r) => r.conclusion === "failure").length - neverStartedCount;
192
252
  return {
193
253
  schemaVersion: RED_BUILDS_SCHEMA,
194
254
  repository,
@@ -196,11 +256,12 @@ export function summarise(repository, runs, rows, stoppedEarly, neverStarted = 0
196
256
  window: times.length ? { from: times[0], to: times.at(-1) } : null,
197
257
  pullRequestRuns: runs.length,
198
258
  redRuns: red,
199
- neverStarted,
259
+ neverStarted: neverStartedCount,
200
260
  analysed: rows.length,
201
261
  unreadable: red - rows.length,
202
262
  verdicts,
203
263
  agentWrittenPreventable: rows.filter((r) => r.verdict === "preventable" && r.agent?.written).length,
264
+ byBranchAgent: sliceByBranchAgent(runs, rows, neverStartedIds),
204
265
  stoppedEarly,
205
266
  rows,
206
267
  };
@@ -222,6 +283,24 @@ const NOTES = {
222
283
  function pct(part, whole) {
223
284
  return whole ? `${Math.round((part / whole) * 100)}%` : "0%";
224
285
  }
286
+ /** A table of the per-agent split, shown only when some branch is named after a coding agent. */
287
+ function formatBranchAgents(report) {
288
+ const agents = Object.keys(report.byBranchAgent).filter((key) => key !== NO_AGENT_BRANCH).sort();
289
+ if (agents.length === 0)
290
+ return [];
291
+ const lines = ["", `${"By branch prefix".padEnd(20)}${"PR runs".padStart(9)}${"red".padStart(12)}${"preventable".padStart(16)}`];
292
+ for (const key of [...agents, NO_AGENT_BRANCH]) {
293
+ const slice = report.byBranchAgent[key];
294
+ if (!slice)
295
+ continue;
296
+ const label = key === NO_AGENT_BRANCH ? "other branches" : `${key}/...`;
297
+ const red = `${slice.redRuns} (${pct(slice.redRuns, slice.pullRequestRuns)})`;
298
+ const preventable = `${slice.verdicts.preventable} of ${slice.analysed}`;
299
+ lines.push(` ${label.padEnd(18)}${String(slice.pullRequestRuns).padStart(9)}${red.padStart(12)}${preventable.padStart(16)}`);
300
+ }
301
+ lines.push("Agents that use ordinary branch names count under other branches.");
302
+ return lines;
303
+ }
225
304
  export function formatReport(report) {
226
305
  const lines = [`DiffCI red-build check: ${report.repository}${report.workflow ? ` · workflow "${report.workflow}"` : ""}`];
227
306
  if (!report.window) {
@@ -249,7 +328,7 @@ export function formatReport(report) {
249
328
  }
250
329
  const p = report.verdicts.preventable.runs;
251
330
  const likely = report.verdicts.likely.runs;
252
- 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");
331
+ 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.", ...formatBranchAgents(report), "", "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");
253
332
  if (report.stoppedEarly)
254
333
  lines.push("", `Stopped early: ${report.stoppedEarly}. The figures cover what was read.`);
255
334
  return lines.join("\n");
@@ -295,9 +374,29 @@ export function githubClient(token, options = {}) {
295
374
  };
296
375
  }
297
376
  /** Workflows that run on pull requests but are not the test CI: scanners, previews, benchmarks, bots. */
298
- 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;
377
+ 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|end ?(to|2) ?end|playwright|cypress|lighthouse|dependabot|renovate|cla|dco|changeset|storybook|chromatic|clean(up)?|caches?|housekeeping|perf(ormance)?|ios|android)\b/i;
299
378
  /** Names and file names the main pull request CI usually has. */
300
- const MAIN_WORKFLOW = /\b(ci|cd|tests?|pipeline|pr|pull[-_ ]request|build|checks?|main|verify|validate|unit|lint|quality)\b/i;
379
+ const MAIN_WORKFLOW = /\b(ci|cd|tests?|pipeline|pr|pull[-_ ]request|build|checks?|main|verify|validate|unit|unittests?|lint|quality)\b/i;
380
+ /** Test words: a tie-breaker between two CI-looking workflows of about the same weight (unit tests over lint). */
381
+ const TEST_WORKFLOW = /\b(tests?|unit|unittests?|ci)\b/i;
382
+ /** Runs that waited for approval or never ran: their wall-clock time is waiting, not CI. */
383
+ const IDLE_CONCLUSION = new Set(["action_required", "skipped", "startup_failure"]);
384
+ /** No real pull request run takes longer; a longer span is a run left waiting or queued. */
385
+ const MAX_RUN_MINUTES = 360;
386
+ /** True when every word of the name is a generic CI word ("PR Checks", "Test CI", "02-unittest"), so it is
387
+ * the repository's main CI rather than one sub-project's ("CLI PR Checks"). */
388
+ function genericName(name) {
389
+ const words = name.toLowerCase().split(/[^a-z]+/).filter(Boolean);
390
+ return words.length > 0 && words.every((word) => MAIN_WORKFLOW.test(word) || word === "and" || word === "run");
391
+ }
392
+ function workflowScore(name, path, minutes) {
393
+ const text = `${name} ${path.replace(/\.ya?ml$/, "").replace(/[-_.]/g, " ")}`;
394
+ const notMain = NOT_MAIN_WORKFLOW.test(text);
395
+ const main = MAIN_WORKFLOW.test(text) && !notMain;
396
+ const score = (minutes + 0.01) * (notMain ? 0.05 : 1) * (MAIN_WORKFLOW.test(text) ? 2 : 1)
397
+ * (main && TEST_WORKFLOW.test(text) ? 1.05 : 1) * (main && genericName(name) ? 1.5 : 1);
398
+ return { score, main };
399
+ }
301
400
  /**
302
401
  * The main pull request CI among one sample page of runs: wall-clock minutes per workflow, doubled when
303
402
  * its name or file looks like CI and cut to 5% when it looks like a scanner, preview, benchmark or bot.
@@ -309,17 +408,30 @@ export function pickMainWorkflow(sample) {
309
408
  const span = (Date.parse(r.updated_at) - Date.parse(r.run_started_at ?? r.created_at)) / 60_000;
310
409
  const path = String(r.path ?? "").replace(/^\.github\/workflows\//, "");
311
410
  const entry = weight.get(r.workflow_id) ?? { name: String(r.name ?? r.workflow_id), path, minutes: 0 };
312
- entry.minutes += Number.isFinite(span) && span > 0 ? span : 0;
411
+ if (!IDLE_CONCLUSION.has(r.conclusion) && Number.isFinite(span) && span > 0)
412
+ entry.minutes += Math.min(span, MAX_RUN_MINUTES);
313
413
  weight.set(r.workflow_id, entry);
314
414
  }
315
415
  let best;
316
416
  for (const [id, w] of weight) {
317
- const text = `${w.name} ${w.path.replace(/\.ya?ml$/, "").replace(/[-_.]/g, " ")}`;
318
- const score = (w.minutes + 0.01) * (NOT_MAIN_WORKFLOW.test(text) ? 0.05 : 1) * (MAIN_WORKFLOW.test(text) ? 2 : 1);
417
+ const { score, main } = workflowScore(w.name, w.path, w.minutes);
319
418
  if (!best || score > best.score)
320
- best = { id, name: w.name, path: w.path, score };
419
+ best = { id, name: w.name, path: w.path, score, main };
321
420
  }
322
- return best && { id: best.id, name: best.name, path: best.path };
421
+ return best && { id: best.id, name: best.name, path: best.path, confident: best.main };
422
+ }
423
+ /** Likely main CI workflows from the repository's workflow list, best first, for a --workflow suggestion. */
424
+ export function suggestWorkflows(workflows) {
425
+ return workflows
426
+ .filter((w) => w.state === "active" && String(w.path ?? "").startsWith(".github/workflows/"))
427
+ .map((w) => {
428
+ const file = String(w.path).replace(/^\.github\/workflows\//, "");
429
+ return { file, name: String(w.name ?? file), ...workflowScore(String(w.name ?? file), file, 1) };
430
+ })
431
+ .filter((w) => w.main)
432
+ .sort((a, b) => b.score - a.score || a.name.length - b.name.length)
433
+ .slice(0, 5)
434
+ .map((w) => `${w.file} ("${w.name}")`);
323
435
  }
324
436
  /** Fetches runs, jobs, annotations and commit messages, then classifies. Partial data on a stop. */
325
437
  export async function collectRedBuilds(options) {
@@ -344,6 +456,12 @@ export async function collectRedBuilds(options) {
344
456
  const chosen = pickMainWorkflow(body?.workflow_runs ?? []);
345
457
  if (!chosen)
346
458
  return summarise(repository, [], [], null);
459
+ if (!chosen.confident) {
460
+ // Only scanners, cleanups or bots ran in the sample: guessing would analyse the wrong workflow.
461
+ const list = await get(`repos/${repository}/actions/workflows?per_page=100`);
462
+ const suggestions = list.status === 200 ? suggestWorkflows(list.body?.workflows ?? []) : [];
463
+ throw new Error(`no workflow among the latest pull request runs looks like the main CI (the busiest was "${chosen.name}", ${chosen.path}). Pass --workflow <file>${suggestions.length ? `; likely candidates: ${suggestions.join(", ")}` : ""}`);
464
+ }
347
465
  workflow = String(chosen.id);
348
466
  workflowLabel = chosen.name;
349
467
  log(`Using the "${workflowLabel}" workflow (${chosen.path}), which looks like the main pull request CI. Pass --workflow to choose another.`);
@@ -390,7 +508,7 @@ export async function collectRedBuilds(options) {
390
508
  if (readable)
391
509
  jobs.set(run.id, list);
392
510
  }
393
- const checkJobs = red.flatMap((run) => (jobs.get(run.id) ?? []).filter((j) => (j.conclusion === "failure" || j.conclusion === "timed_out") && bucketJob(j, patterns) === "check"));
511
+ const checkJobs = red.flatMap((run) => (jobs.get(run.id) ?? []).filter((j) => (j.conclusion === "failure" || j.conclusion === "timed_out") && bucketJob(j, patterns, run.workflowName) === "check"));
394
512
  log(`Reading failure annotations of ${checkJobs.length} failing check jobs...`);
395
513
  for (const job of checkJobs) {
396
514
  const { status, body } = await get(`repos/${repository}/check-runs/${job.id}/annotations?per_page=50`);
@@ -424,7 +542,7 @@ export async function collectRedBuilds(options) {
424
542
  stoppedEarly = error.message;
425
543
  }
426
544
  }
427
- const neverStarted = runs.filter((r) => r.conclusion === "failure" && jobs.has(r.id) && nothingRan(jobs.get(r.id))).length;
545
+ const neverStarted = new Set(runs.filter((r) => r.conclusion === "failure" && jobs.has(r.id) && nothingRan(jobs.get(r.id))).map((r) => r.id));
428
546
  const report = summarise(repository, runs, rows, stoppedEarly, neverStarted);
429
547
  report.workflow = workflowLabel || runs[0]?.workflowName || null;
430
548
  return report;
@@ -442,7 +560,8 @@ export const RED_BUILDS_USAGE = `Usage: diffci red-builds <owner/repo> [--runs <
442
560
  How many of a repository's red pull request builds failed on checks the author could have run before
443
561
  pushing. Reads GitHub Actions history (read-only, paced) and runs nothing. Needs a GitHub token:
444
562
  GITHUB_TOKEN, GH_TOKEN, or a signed-in gh CLI. --runs: most recent pull request runs to read (default 200,
445
- max 1000). --check-jobs / --ci-only-jobs: regexes that override which job names count as local checks.`;
563
+ max 1000). --check-jobs / --ci-only-jobs: regexes that override which job names count as local checks.
564
+ Runs on branches named after a coding agent (copilot/, claude/, codex/...) are also counted per agent.`;
446
565
  /** Entry point for `diffci red-builds`. Returns the exit code: 0 on a report, 2 on bad input or errors. */
447
566
  export async function runRedBuildsCommand(args, env = process.env, deps = {}) {
448
567
  let repository;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@diffci.com/diffci",
3
- "version": "0.3.44",
3
+ "version": "0.3.46",
4
4
  "description": "Verification for AI coding agents: runs the tests and checks a change affects, with full fallback and a receipt",
5
5
  "keywords": [
6
6
  "ci",