@diffci.com/diffci 0.3.43 → 0.3.45

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.
@@ -15,9 +15,17 @@ export declare function ignoredWrites(repoPath: string, results: readonly string
15
15
  * instruction. Growth depends on the agent finding DiffCI's tools in the repository without anyone
16
16
  * installing a plugin, so one `diffci init` now registers them. Each write keeps files and servers
17
17
  * DiffCI did not write.
18
+ *
19
+ * 2026-11-14: also the hyperscalers' coding agents. Kiro gets `.kiro/settings/mcp.json` (the read-only
20
+ * tools auto-approved; it still asks before tests run) and `.kiro/skills`; Antigravity CLI gets
21
+ * `.agents/mcp_config.json` and `.agents/skills`, which Codex reads too. GitHub Copilot needs no file of
22
+ * its own for these: VS Code reads the root `.mcp.json`, and Copilot reads `.claude/skills`.
18
23
  */
19
- export declare const MCP_CONFIG_PATHS: readonly [".mcp.json", ".cursor/mcp.json"];
24
+ export declare const MCP_CONFIG_PATHS: readonly [".mcp.json", ".cursor/mcp.json", ".kiro/settings/mcp.json", ".agents/mcp_config.json"];
20
25
  export declare const SKILL_PATH = ".claude/skills/diffci-verify/SKILL.md";
26
+ export declare const SKILL_PATHS: readonly [".claude/skills/diffci-verify/SKILL.md", ".agents/skills/diffci-verify/SKILL.md", ".kiro/skills/diffci-verify/SKILL.md"];
27
+ /** MCP tools that only read the checkout; Kiro runs them without asking. */
28
+ export declare const KIRO_AUTO_APPROVE: readonly ["diffci_changed_files", "diffci_select_tests", "diffci_explain_selection"];
21
29
  /** Same launcher as the portable agent plugin: `npx` through cmd.exe on Windows, where agents cannot spawn `npx.cmd` directly. */
22
30
  export declare function mcpServerEntry(version: string): {
23
31
  command: string;
@@ -32,10 +40,16 @@ export declare const DIFFCI_VERIFY_SKILL = "---\nname: diffci-verify\ndescriptio
32
40
  * agent's project hook file. Claude Code and Codex share one shape (`Stop` > group > handlers); Cursor has
33
41
  * its own (`version: 1`, `stop` > handlers). A hook is DiffCI's when its command runs `agent-stop` from
34
42
  * the DiffCI package; those are replaced, every other hook is kept.
43
+ *
44
+ * GitHub Copilot (2026-11-14): `agentStop` in `.github/hooks/diffci.json` (`version: 1`, handlers with
45
+ * `bash` and `powershell` commands), read by Copilot CLI, the cloud agent and VS Code. Its documented
46
+ * `{"decision": "block", "reason"}` output forces another turn. Kiro has no hook here: its `Stop`
47
+ * trigger is documented as unable to block, so it could not make the agent fix a failure.
35
48
  */
36
- export declare const AGENT_HOOK_PATHS: Record<"claude" | "codex" | "cursor", string>;
49
+ export type SetupHookAgent = "claude" | "codex" | "cursor" | "copilot";
50
+ export declare const AGENT_HOOK_PATHS: Record<SetupHookAgent, string>;
37
51
  /** Seconds the agent waits for the hook; verify's own timeout stays below it (cli.ts, agent-stop). */
38
52
  export declare const AGENT_HOOK_TIMEOUT_SECONDS = 1200;
39
- export declare function writeAgentStopHook(repoPath: string, agent: "claude" | "codex" | "cursor", launcher: string): string;
53
+ export declare function writeAgentStopHook(repoPath: string, agent: SetupHookAgent, launcher: string): string;
40
54
  /** A skill file DiffCI wrote is recognised by its frontmatter name and updated; any other file is kept. */
41
- export declare function writeSkill(repoPath: string, force: boolean): string;
55
+ export declare function writeSkill(repoPath: string, force: boolean, relativePath?: string): string;
@@ -32,9 +32,22 @@ export function ignoredWrites(repoPath, results) {
32
32
  * instruction. Growth depends on the agent finding DiffCI's tools in the repository without anyone
33
33
  * installing a plugin, so one `diffci init` now registers them. Each write keeps files and servers
34
34
  * DiffCI did not write.
35
+ *
36
+ * 2026-11-14: also the hyperscalers' coding agents. Kiro gets `.kiro/settings/mcp.json` (the read-only
37
+ * tools auto-approved; it still asks before tests run) and `.kiro/skills`; Antigravity CLI gets
38
+ * `.agents/mcp_config.json` and `.agents/skills`, which Codex reads too. GitHub Copilot needs no file of
39
+ * its own for these: VS Code reads the root `.mcp.json`, and Copilot reads `.claude/skills`.
35
40
  */
36
- export const MCP_CONFIG_PATHS = [".mcp.json", ".cursor/mcp.json"];
41
+ export const MCP_CONFIG_PATHS = [".mcp.json", ".cursor/mcp.json", ".kiro/settings/mcp.json", ".agents/mcp_config.json"];
37
42
  export const SKILL_PATH = ".claude/skills/diffci-verify/SKILL.md";
43
+ export const SKILL_PATHS = [SKILL_PATH, ".agents/skills/diffci-verify/SKILL.md", ".kiro/skills/diffci-verify/SKILL.md"];
44
+ const SKILL_AGENTS = {
45
+ [SKILL_PATH]: "Claude Code and Copilot skill",
46
+ ".agents/skills/diffci-verify/SKILL.md": "Antigravity CLI and Codex skill",
47
+ ".kiro/skills/diffci-verify/SKILL.md": "Kiro skill",
48
+ };
49
+ /** MCP tools that only read the checkout; Kiro runs them without asking. */
50
+ export const KIRO_AUTO_APPROVE = ["diffci_changed_files", "diffci_select_tests", "diffci_explain_selection"];
38
51
  /** Same launcher as the portable agent plugin: `npx` through cmd.exe on Windows, where agents cannot spawn `npx.cmd` directly. */
39
52
  export function mcpServerEntry(version) {
40
53
  return {
@@ -52,6 +65,8 @@ function isDiffciEntry(entry) {
52
65
  export function writeMcpConfig(repoPath, relativePath, version, force) {
53
66
  const absolutePath = join(repoPath, relativePath);
54
67
  const entry = mcpServerEntry(version);
68
+ if (relativePath === ".kiro/settings/mcp.json")
69
+ entry.autoApprove = [...KIRO_AUTO_APPROVE];
55
70
  let config = {};
56
71
  let existing;
57
72
  if (existsSync(absolutePath)) {
@@ -115,16 +130,11 @@ counts, outcome, and any outstanding required checks. Never infer passed suites,
115
130
  test cases, skipped CI jobs, or measured savings from selection counts. Required
116
131
  project CI stays authoritative.
117
132
  `;
118
- /**
119
- * Stop hooks that run `diffci agent-stop` when the agent ends a turn (agent-stop.ts, 2026-11-06), in each
120
- * agent's project hook file. Claude Code and Codex share one shape (`Stop` > group > handlers); Cursor has
121
- * its own (`version: 1`, `stop` > handlers). A hook is DiffCI's when its command runs `agent-stop` from
122
- * the DiffCI package; those are replaced, every other hook is kept.
123
- */
124
133
  export const AGENT_HOOK_PATHS = {
125
134
  claude: ".claude/settings.json",
126
135
  codex: ".codex/hooks.json",
127
136
  cursor: ".cursor/hooks.json",
137
+ copilot: ".github/hooks/diffci.json",
128
138
  };
129
139
  /** Seconds the agent waits for the hook; verify's own timeout stays below it (cli.ts, agent-stop). */
130
140
  export const AGENT_HOOK_TIMEOUT_SECONDS = 1200;
@@ -154,6 +164,15 @@ export function writeAgentStopHook(repoPath, agent, launcher) {
154
164
  const stop = Array.isArray(hooks.stop) ? hooks.stop.filter((entry) => !isDiffciHook(entry?.command)) : [];
155
165
  config = { ...config, version: typeof config.version === "number" ? config.version : 1, hooks: { ...hooks, stop: [...stop, { command, loop_limit: 3 }] } };
156
166
  }
167
+ else if (agent === "copilot") {
168
+ const ours = (entry) => ["bash", "powershell", "command"].some((key) => isDiffciHook(entry?.[key]));
169
+ const stop = Array.isArray(hooks.agentStop) ? hooks.agentStop.filter((entry) => !ours(entry)) : [];
170
+ config = {
171
+ ...config,
172
+ version: typeof config.version === "number" ? config.version : 1,
173
+ hooks: { ...hooks, agentStop: [...stop, { type: "command", bash: command, powershell: command, timeoutSec: AGENT_HOOK_TIMEOUT_SECONDS }] },
174
+ };
175
+ }
157
176
  else {
158
177
  const groups = (Array.isArray(hooks.Stop) ? hooks.Stop : []).flatMap((group) => {
159
178
  const handlers = Array.isArray(group?.hooks) ? group.hooks : [];
@@ -170,19 +189,19 @@ export function writeAgentStopHook(repoPath, agent, launcher) {
170
189
  return `${existing === undefined ? "wrote" : "updated"} ${relativePath} (DiffCI stop hook)`;
171
190
  }
172
191
  /** A skill file DiffCI wrote is recognised by its frontmatter name and updated; any other file is kept. */
173
- export function writeSkill(repoPath, force) {
174
- const absolutePath = join(repoPath, SKILL_PATH);
192
+ export function writeSkill(repoPath, force, relativePath = SKILL_PATH) {
193
+ const absolutePath = join(repoPath, relativePath);
175
194
  if (existsSync(absolutePath)) {
176
195
  const existing = readFileSync(absolutePath, "utf8");
177
196
  if (existing.replace(/\r\n/g, "\n") === DIFFCI_VERIFY_SKILL)
178
- return `kept ${SKILL_PATH} (current)`;
197
+ return `kept ${relativePath} (current)`;
179
198
  if (!/^---\r?\nname: diffci-verify\r?\n/.test(existing) && !force) {
180
- return `kept ${SKILL_PATH} (existing file not written by DiffCI; pass --force to replace it)`;
199
+ return `kept ${relativePath} (existing file not written by DiffCI; pass --force to replace it)`;
181
200
  }
182
201
  writeFileSync(absolutePath, DIFFCI_VERIFY_SKILL, "utf8");
183
- return `updated ${SKILL_PATH}`;
202
+ return `updated ${relativePath}`;
184
203
  }
185
204
  mkdirSync(dirname(absolutePath), { recursive: true });
186
205
  writeFileSync(absolutePath, DIFFCI_VERIFY_SKILL, "utf8");
187
- return `wrote ${SKILL_PATH} (Claude Code skill)`;
206
+ return `wrote ${relativePath} (${SKILL_AGENTS[relativePath] ?? "skill"})`;
188
207
  }
@@ -6,24 +6,26 @@ import type { VerificationReport } from "./verify.js";
6
6
  * verify is advice an agent can skip; a hook on the end of its turn is not. The agent finds out what its
7
7
  * change broke before it tells anyone the work is done.
8
8
  *
9
- * WHAT. `diffci agent-stop --agent claude|codex|cursor` is the command the agent's stop hook runs
9
+ * WHAT. `diffci agent-stop --agent claude|codex|cursor|copilot` is the command the agent's stop hook runs
10
10
  * (Claude Code `Stop` in .claude/settings.json, Codex `Stop` in .codex/hooks.json, Cursor `stop` in
11
- * .cursor/hooks.json; `diffci init` installs them). It reads the hook's JSON from stdin, verifies the
11
+ * .cursor/hooks.json, GitHub Copilot `agentStop` in .github/hooks/diffci.json; `diffci init` installs them). It reads the hook's JSON from stdin, verifies the
12
12
  * uncommitted changes, and:
13
13
  * - passes quietly when nothing changed or verification passed;
14
14
  * - when tests or checks fail, asks the agent to continue with the failures as the reason (Claude Code
15
- * and Codex: `{"decision": "block", "reason"}`; Cursor: `{"followup_message"}`);
15
+ * Codex and Copilot: `{"decision": "block", "reason"}`; Cursor: `{"followup_message"}`);
16
16
  * - never holds the agent when verification could not run (blocked analysis, no command): that is
17
17
  * reported to the person, not turned into work for the agent;
18
18
  * - hands back to the person after DIFFCI_AGENT_HOOK_MAX failed attempts in one session (default 3),
19
19
  * counted in .git/diffci/agent-hook.json and reset by a pass, on top of the agents' own loop limits.
20
20
  * DIFFCI_AGENT_HOOK=0 turns it off. Repeats on an unchanged tree are instant through result reuse.
21
21
  */
22
- export type HookAgent = "claude" | "codex" | "cursor";
22
+ export type HookAgent = "claude" | "codex" | "cursor" | "copilot";
23
23
  export declare const HOOK_AGENTS: readonly HookAgent[];
24
24
  export declare const DEFAULT_MAX_ATTEMPTS = 3;
25
25
  export interface StopPayload {
26
26
  session_id?: string;
27
+ /** GitHub Copilot's `agentStop` payload. */
28
+ sessionId?: string;
27
29
  conversation_id?: string;
28
30
  cwd?: string;
29
31
  workspace_roots?: string[];
@@ -2,7 +2,7 @@ import { execFileSync } from "node:child_process";
2
2
  import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
3
3
  import { dirname, join } from "node:path";
4
4
  import { outcomeLogPath } from "./outcome-log.js";
5
- export const HOOK_AGENTS = ["claude", "codex", "cursor"];
5
+ export const HOOK_AGENTS = ["claude", "codex", "cursor", "copilot"];
6
6
  export const DEFAULT_MAX_ATTEMPTS = 3;
7
7
  export function parseStopPayload(text) {
8
8
  try {
@@ -24,7 +24,7 @@ export function stopRepoPath(payload, env, fallback) {
24
24
  }
25
25
  }
26
26
  function sessionKey(payload) {
27
- return payload.session_id ?? payload.conversation_id ?? "unknown";
27
+ return payload.session_id ?? payload.sessionId ?? payload.conversation_id ?? "unknown";
28
28
  }
29
29
  function attemptsPath(repoPath) {
30
30
  const log = outcomeLogPath(repoPath);
@@ -76,7 +76,8 @@ function failureReason(report, attempt, max) {
76
76
  */
77
77
  export function decideStop(agent, report, failuresSoFar, max) {
78
78
  const allow = (message) => ({
79
- stdout: JSON.stringify(message && agent !== "cursor" ? { systemMessage: message } : {}),
79
+ // Cursor and Copilot document no field for a message to the person.
80
+ stdout: JSON.stringify(message && agent !== "cursor" && agent !== "copilot" ? { systemMessage: message } : {}),
80
81
  failures: 0,
81
82
  });
82
83
  if (!report)
@@ -47,7 +47,7 @@ import { resolveObservationAgent } from "./agent-identity.js";
47
47
  import { inferFullCommand, inferComparableSelectedCommand, inferWorkspaceComparison } from "./full-command.js";
48
48
  import { addDiffciPackageScripts, detectPackageManager, installDiffci } from "./install.js";
49
49
  import { hookCommand, installPrePushHook, isGitRepository } from "./hook.js";
50
- import { AGENT_HOOK_TIMEOUT_SECONDS, ignoredWrites, MCP_CONFIG_PATHS, SKILL_PATH, writeAgentStopHook, writeMcpConfig, writeSkill } from "./agent-setup.js";
50
+ import { AGENT_HOOK_TIMEOUT_SECONDS, ignoredWrites, MCP_CONFIG_PATHS, SKILL_PATHS, writeAgentStopHook, writeMcpConfig, writeSkill } from "./agent-setup.js";
51
51
  import { submitObservation } from "./submit.js";
52
52
  import { configureGraphCache } from "./shared-graph-cache.js";
53
53
  import { GraphCache } from "@diffci.com/core/cache/graph-cache";
@@ -422,9 +422,10 @@ function runInit(flags, env) {
422
422
  for (const path of MCP_CONFIG_PATHS)
423
423
  writes.push(writeMcpConfig(repoPath, path, identity.version, force));
424
424
  if (flags["no-skill"] === true)
425
- skipped.push(`skipped ${SKILL_PATH} (--no-skill)`);
425
+ skipped.push("skipped the diffci-verify skills (--no-skill)");
426
426
  else
427
- writes.push(writeSkill(repoPath, force));
427
+ for (const path of SKILL_PATHS)
428
+ writes.push(writeSkill(repoPath, force, path));
428
429
  if (flags["no-agent-hooks"] === true)
429
430
  skipped.push("skipped the agent stop hooks (--no-agent-hooks)");
430
431
  else
@@ -1421,7 +1422,7 @@ Usage:
1421
1422
  diffci init [--repo <path>] [--workflow] [--verification-workflow] [--install] [--no-hook] [--no-mcp] [--no-skill]
1422
1423
  [--no-agent-hooks] [--force]
1423
1424
  diffci watch [--repo <path>] [--checks] [--debounce-ms <ms>] [--no-log]
1424
- diffci agent-stop --agent claude|codex|cursor (run by the agent stop hooks init installs; reads the hook JSON on stdin)
1425
+ diffci agent-stop --agent claude|codex|cursor|copilot (run by the agent stop hooks init installs; reads the hook JSON on stdin)
1425
1426
  diffci mcp
1426
1427
  diffci verify [--changed | --base <sha> --head <sha>] [--policy enforce] [--repo <path>] [--out <file>] [--json]
1427
1428
  [--redact-paths] [--timeout-ms <ms>] [--baseline-on-failure] [--no-checks | --checks]
@@ -1459,9 +1460,11 @@ Usage:
1459
1460
  diffci version
1460
1461
 
1461
1462
  init writes AGENTS.md, CLAUDE.md, Cursor rules, Copilot instructions, and diffci.config.json. It also
1462
- registers the DiffCI MCP server in .mcp.json (Claude Code) and .cursor/mcp.json (Cursor), keeping other
1463
- servers, adds the diffci-verify skill to .claude/skills, installs the pre-push hook, and adds stop hooks
1464
- (.claude/settings.json, .codex/hooks.json, .cursor/hooks.json) that run diffci agent-stop when an agent ends a
1463
+ registers the DiffCI MCP server in .mcp.json (Claude Code, VS Code), .cursor/mcp.json (Cursor),
1464
+ .kiro/settings/mcp.json (Kiro) and .agents/mcp_config.json (Antigravity CLI), keeping other servers, adds the
1465
+ diffci-verify skill to .claude/skills, .agents/skills and .kiro/skills, installs the pre-push hook, and adds stop
1466
+ hooks (.claude/settings.json, .codex/hooks.json, .cursor/hooks.json, .github/hooks/diffci.json for GitHub
1467
+ Copilot) that run diffci agent-stop when an agent ends a
1465
1468
  turn: it verifies the uncommitted changes and, when tests or checks fail, asks the agent to fix them before
1466
1469
  finishing, at most DIFFCI_AGENT_HOOK_MAX times a session (default 3; DIFFCI_AGENT_HOOK=0 turns it off).
1467
1470
  --no-mcp, --no-skill, --no-hook and --no-agent-hooks leave each out. --workflow adds a separate non-blocking observation workflow. --install detects npm, pnpm, Yarn,
@@ -32,10 +32,13 @@ export interface Patterns {
32
32
  ciOnlyJob: RegExp;
33
33
  }
34
34
  export declare const DEFAULT_PATTERNS: Patterns;
35
- export declare function bucketJob(job: JobSummary, patterns?: Patterns): JobBucket;
35
+ export declare function bucketJob(job: JobSummary, patterns?: Patterns, workflowName?: string): JobBucket;
36
36
  export declare function isAggregateJob(job: JobSummary): boolean;
37
37
  /** Failure signatures of one job: annotation path, title and first message line, with volatile parts blurred. */
38
38
  export declare function signatures(annotations: Annotation[]): Set<string>;
39
+ /** A red run where no job started (zero jobs, or all skipped): a workflow that failed to start, typically a fork
40
+ * PR's run that GitHub rejected. Nothing was checked, so it is not a red build of the change. */
41
+ export declare function nothingRan(jobs: JobSummary[]): boolean;
39
42
  export interface RedRun {
40
43
  run: number;
41
44
  workflow: string;
@@ -79,7 +82,10 @@ export interface RedBuildsReport {
79
82
  to: string;
80
83
  } | null;
81
84
  pullRequestRuns: number;
85
+ /** Red runs where at least one job ran. */
82
86
  redRuns: number;
87
+ /** Runs GitHub marked failed although no job started (workflow startup failures); left out of redRuns. */
88
+ neverStarted: number;
83
89
  analysed: number;
84
90
  unreadable: number;
85
91
  verdicts: Record<Verdict, {
@@ -90,7 +96,7 @@ export interface RedBuildsReport {
90
96
  stoppedEarly: string | null;
91
97
  rows: RedRun[];
92
98
  }
93
- export declare function summarise(repository: string, runs: RunSummary[], rows: RedRun[], stoppedEarly: string | null): RedBuildsReport;
99
+ export declare function summarise(repository: string, runs: RunSummary[], rows: RedRun[], stoppedEarly: string | null, neverStarted?: number): RedBuildsReport;
94
100
  export declare function formatReport(report: RedBuildsReport): string;
95
101
  export type GitHubGet = (path: string) => Promise<{
96
102
  status: number;
@@ -114,7 +120,10 @@ export declare function pickMainWorkflow(sample: any[]): {
114
120
  id: number;
115
121
  name: string;
116
122
  path: string;
123
+ confident: boolean;
117
124
  } | undefined;
125
+ /** Likely main CI workflows from the repository's workflow list, best first, for a --workflow suggestion. */
126
+ export declare function suggestWorkflows(workflows: any[]): string[];
118
127
  export interface CollectOptions {
119
128
  repository: string;
120
129
  get: GitHubGet;
@@ -35,6 +35,11 @@ const CHECK_JOB = /\b(lint(ing)?|eslint|biome|prettier|format(ting)?|fmt|style|t
35
35
  /** Aggregate gate jobs ("all required jobs passed"): they fail because another job did, so they are ignored
36
36
  * whenever another job in the same run failed too. */
37
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
+ /** Gate jobs named after what they check: "Unit Tests - Status Check", "require-all-checks-to-pass". */
39
+ const AGGREGATE_SUFFIX = /(^|\s-\s|\s)(status[- ]checks?|requires?d?[- ]all[- ]checks?([- ]to)?[- ](pass(ed)?|succeed(ed)?))$/i;
40
+ /** Workflows whose every job is a local check, so a job named only by its matrix ("JavaScript (Node.js 24)
41
+ * 1/4") inherits the workflow's kind. Kept narrow: a workflow called "CI" or "Build and Test" says nothing. */
42
+ const LOCAL_CHECK_WORKFLOW = /\b(unit[- ]?tests?|lint(ing)?|typecheck|type[- ]?checks?|static[- ]analysis)\b/i;
38
43
  const CI_ONLY_STEP = /lockfile|lock file|migration ordering/i;
39
44
  const GENERIC_ANNOTATION = /process completed with exit code|^command failed|elifecycle|exited with code/i;
40
45
  const TIMEOUT = /timed out|timeout/i;
@@ -42,7 +47,7 @@ const AGENT_TRAILER = /co-authored-by:[^\n]*?\b(claude|cursor|copilot|codex|devi
42
47
  const AGENT_BRANCH = /^(claude|codex|copilot|cursor|devin|jules)[/-]/i;
43
48
  export const VERDICTS = ["preventable", "partly", "likely", "shared", "ci-only", "flaky", "infra"];
44
49
  export const DEFAULT_PATTERNS = { checkJob: CHECK_JOB, ciOnlyJob: CI_ONLY_JOB };
45
- export function bucketJob(job, patterns = DEFAULT_PATTERNS) {
50
+ export function bucketJob(job, patterns = DEFAULT_PATTERNS, workflowName = "") {
46
51
  if (job.failedSteps.length === 0)
47
52
  return "infra"; // cancelled, timed out or runner lost: no step failed
48
53
  if (job.failedSteps.every((step) => INFRA_STEP.test(step)))
@@ -57,6 +62,8 @@ export function bucketJob(job, patterns = DEFAULT_PATTERNS) {
57
62
  return "ci-only";
58
63
  if (patterns.checkJob.test(name))
59
64
  return "check";
65
+ if (LOCAL_CHECK_WORKFLOW.test(workflowName) && !CI_ONLY_STRONG.test(workflowName) && !patterns.ciOnlyJob.test(name))
66
+ return "check";
60
67
  return "ci-only"; // a CI-side job by name, or one matching neither list: never inflates the preventable count
61
68
  }
62
69
  /** The job's own name, without a "Workflow / " or "caller / " prefix. */
@@ -64,7 +71,8 @@ function jobName(job) {
64
71
  return (job.name.split(" / ").at(-1) ?? job.name).trim();
65
72
  }
66
73
  export function isAggregateJob(job) {
67
- return AGGREGATE_JOB.test(jobName(job).replace(/[()]/g, "").trim());
74
+ const name = jobName(job).replace(/[()]/g, "").trim();
75
+ return AGGREGATE_JOB.test(name) || AGGREGATE_SUFFIX.test(name);
68
76
  }
69
77
  /** Failure signatures of one job: annotation path, title and first message line, with volatile parts blurred. */
70
78
  export function signatures(annotations) {
@@ -82,6 +90,11 @@ export function signatures(annotations) {
82
90
  }
83
91
  return out;
84
92
  }
93
+ /** A red run where no job started (zero jobs, or all skipped): a workflow that failed to start, typically a fork
94
+ * PR's run that GitHub rejected. Nothing was checked, so it is not a red build of the change. */
95
+ export function nothingRan(jobs) {
96
+ return jobs.every((job) => !job.startedAt || job.conclusion === "skipped");
97
+ }
85
98
  function minutes(job) {
86
99
  if (!job.startedAt || !job.completedAt)
87
100
  return 0;
@@ -93,15 +106,19 @@ export function classify(input) {
93
106
  const passed = new Set(input.runs.filter((r) => r.conclusion === "success").map((r) => `${r.workflowId}:${r.headSha}`));
94
107
  const prKey = (r) => `${r.headRepo}:${r.headBranch}`;
95
108
  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.
109
+ // Which PRs each failure signature, and each failing check job, appeared on across the whole window.
97
110
  const seen = new Map();
111
+ const jobFailedOn = new Map();
98
112
  for (const run of input.runs) {
99
113
  const jobs = input.jobs.get(run.id);
100
114
  if (run.conclusion !== "failure" || !jobs)
101
115
  continue;
102
116
  for (const job of failingOf(jobs)) {
103
- if (bucketJob(job, patterns) !== "check")
117
+ if (bucketJob(job, patterns, run.workflowName) !== "check")
104
118
  continue;
119
+ if (!jobFailedOn.has(job.name))
120
+ jobFailedOn.set(job.name, new Set());
121
+ jobFailedOn.get(job.name).add(prKey(run));
105
122
  for (const sig of signatures(input.annotations.get(job.id) ?? [])) {
106
123
  if (!seen.has(sig))
107
124
  seen.set(sig, new Set());
@@ -109,23 +126,30 @@ export function classify(input) {
109
126
  }
110
127
  }
111
128
  }
129
+ // A check job with no annotations that fails on most pull requests is broken for everyone, not for this
130
+ // change (continue's jetbrains-tests failed on all 185 red runs). It counts as shared, never as own.
131
+ const prs = new Set(input.runs.map(prKey)).size;
132
+ const brokenForEveryone = (name) => {
133
+ const failedOn = jobFailedOn.get(name)?.size ?? 0;
134
+ return failedOn >= 5 && failedOn * 2 >= prs;
135
+ };
112
136
  const rows = [];
113
137
  for (const run of input.runs) {
114
138
  const jobs = input.jobs.get(run.id);
115
- if (run.conclusion !== "failure" || !jobs)
139
+ if (run.conclusion !== "failure" || !jobs || nothingRan(jobs))
116
140
  continue;
117
141
  const allFailing = failingOf(jobs);
118
142
  // A gate job that only reports "something else failed" says nothing on its own.
119
143
  const failing = allFailing.some((j) => !isAggregateJob(j)) ? allFailing.filter((j) => !isAggregateJob(j)) : allFailing;
120
144
  const detail = failing.map((job) => {
121
- const bucket = bucketJob(job, patterns);
145
+ const bucket = bucketJob(job, patterns, run.workflowName);
122
146
  if (bucket !== "check")
123
147
  return { name: job.name, bucket };
124
148
  const annotations = input.annotations.get(job.id);
125
149
  const sigs = signatures(annotations ?? []);
126
150
  let ownership;
127
151
  if (sigs.size === 0)
128
- ownership = "unknown";
152
+ ownership = brokenForEveryone(job.name) ? "shared" : "unknown";
129
153
  else if ([...sigs].every((s) => TIMEOUT.test(s)))
130
154
  ownership = "timeout";
131
155
  else if ([...sigs].some((s) => !TIMEOUT.test(s) && (seen.get(s)?.size ?? 0) > 1))
@@ -174,7 +198,7 @@ export function agentMarker(message, branch) {
174
198
  return { written: true, marker: "branch prefix" };
175
199
  return { written: false, marker: "" };
176
200
  }
177
- export function summarise(repository, runs, rows, stoppedEarly) {
201
+ export function summarise(repository, runs, rows, stoppedEarly, neverStarted = 0) {
178
202
  const verdicts = Object.fromEntries(VERDICTS.map((v) => [v, { runs: 0, runnerMinutes: 0 }]));
179
203
  for (const row of rows) {
180
204
  verdicts[row.verdict].runs++;
@@ -183,7 +207,7 @@ export function summarise(repository, runs, rows, stoppedEarly) {
183
207
  for (const v of VERDICTS)
184
208
  verdicts[v].runnerMinutes = Math.round(verdicts[v].runnerMinutes);
185
209
  const times = runs.map((r) => r.createdAt).sort();
186
- const red = runs.filter((r) => r.conclusion === "failure").length;
210
+ const red = runs.filter((r) => r.conclusion === "failure").length - neverStarted;
187
211
  return {
188
212
  schemaVersion: RED_BUILDS_SCHEMA,
189
213
  repository,
@@ -191,6 +215,7 @@ export function summarise(repository, runs, rows, stoppedEarly) {
191
215
  window: times.length ? { from: times[0], to: times.at(-1) } : null,
192
216
  pullRequestRuns: runs.length,
193
217
  redRuns: red,
218
+ neverStarted,
194
219
  analysed: rows.length,
195
220
  unreadable: red - rows.length,
196
221
  verdicts,
@@ -223,6 +248,8 @@ export function formatReport(report) {
223
248
  return lines.join("\n");
224
249
  }
225
250
  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)})`);
251
+ if (report.neverStarted > 0)
252
+ lines.push(`${report.neverStarted} more runs were marked failed although no job started (the workflow failed to start); they are not counted as red.`);
226
253
  if (report.unreadable > 0)
227
254
  lines.push(`${report.unreadable} red runs could not be read and are left out.`);
228
255
  if (report.analysed === 0) {
@@ -287,9 +314,29 @@ export function githubClient(token, options = {}) {
287
314
  };
288
315
  }
289
316
  /** 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;
317
+ 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;
291
318
  /** 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;
319
+ const MAIN_WORKFLOW = /\b(ci|cd|tests?|pipeline|pr|pull[-_ ]request|build|checks?|main|verify|validate|unit|unittests?|lint|quality)\b/i;
320
+ /** Test words: a tie-breaker between two CI-looking workflows of about the same weight (unit tests over lint). */
321
+ const TEST_WORKFLOW = /\b(tests?|unit|unittests?|ci)\b/i;
322
+ /** Runs that waited for approval or never ran: their wall-clock time is waiting, not CI. */
323
+ const IDLE_CONCLUSION = new Set(["action_required", "skipped", "startup_failure"]);
324
+ /** No real pull request run takes longer; a longer span is a run left waiting or queued. */
325
+ const MAX_RUN_MINUTES = 360;
326
+ /** True when every word of the name is a generic CI word ("PR Checks", "Test CI", "02-unittest"), so it is
327
+ * the repository's main CI rather than one sub-project's ("CLI PR Checks"). */
328
+ function genericName(name) {
329
+ const words = name.toLowerCase().split(/[^a-z]+/).filter(Boolean);
330
+ return words.length > 0 && words.every((word) => MAIN_WORKFLOW.test(word) || word === "and" || word === "run");
331
+ }
332
+ function workflowScore(name, path, minutes) {
333
+ const text = `${name} ${path.replace(/\.ya?ml$/, "").replace(/[-_.]/g, " ")}`;
334
+ const notMain = NOT_MAIN_WORKFLOW.test(text);
335
+ const main = MAIN_WORKFLOW.test(text) && !notMain;
336
+ const score = (minutes + 0.01) * (notMain ? 0.05 : 1) * (MAIN_WORKFLOW.test(text) ? 2 : 1)
337
+ * (main && TEST_WORKFLOW.test(text) ? 1.05 : 1) * (main && genericName(name) ? 1.5 : 1);
338
+ return { score, main };
339
+ }
293
340
  /**
294
341
  * The main pull request CI among one sample page of runs: wall-clock minutes per workflow, doubled when
295
342
  * its name or file looks like CI and cut to 5% when it looks like a scanner, preview, benchmark or bot.
@@ -301,17 +348,30 @@ export function pickMainWorkflow(sample) {
301
348
  const span = (Date.parse(r.updated_at) - Date.parse(r.run_started_at ?? r.created_at)) / 60_000;
302
349
  const path = String(r.path ?? "").replace(/^\.github\/workflows\//, "");
303
350
  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;
351
+ if (!IDLE_CONCLUSION.has(r.conclusion) && Number.isFinite(span) && span > 0)
352
+ entry.minutes += Math.min(span, MAX_RUN_MINUTES);
305
353
  weight.set(r.workflow_id, entry);
306
354
  }
307
355
  let best;
308
356
  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);
357
+ const { score, main } = workflowScore(w.name, w.path, w.minutes);
311
358
  if (!best || score > best.score)
312
- best = { id, name: w.name, path: w.path, score };
359
+ best = { id, name: w.name, path: w.path, score, main };
313
360
  }
314
- return best && { id: best.id, name: best.name, path: best.path };
361
+ return best && { id: best.id, name: best.name, path: best.path, confident: best.main };
362
+ }
363
+ /** Likely main CI workflows from the repository's workflow list, best first, for a --workflow suggestion. */
364
+ export function suggestWorkflows(workflows) {
365
+ return workflows
366
+ .filter((w) => w.state === "active" && String(w.path ?? "").startsWith(".github/workflows/"))
367
+ .map((w) => {
368
+ const file = String(w.path).replace(/^\.github\/workflows\//, "");
369
+ return { file, name: String(w.name ?? file), ...workflowScore(String(w.name ?? file), file, 1) };
370
+ })
371
+ .filter((w) => w.main)
372
+ .sort((a, b) => b.score - a.score || a.name.length - b.name.length)
373
+ .slice(0, 5)
374
+ .map((w) => `${w.file} ("${w.name}")`);
315
375
  }
316
376
  /** Fetches runs, jobs, annotations and commit messages, then classifies. Partial data on a stop. */
317
377
  export async function collectRedBuilds(options) {
@@ -336,6 +396,12 @@ export async function collectRedBuilds(options) {
336
396
  const chosen = pickMainWorkflow(body?.workflow_runs ?? []);
337
397
  if (!chosen)
338
398
  return summarise(repository, [], [], null);
399
+ if (!chosen.confident) {
400
+ // Only scanners, cleanups or bots ran in the sample: guessing would analyse the wrong workflow.
401
+ const list = await get(`repos/${repository}/actions/workflows?per_page=100`);
402
+ const suggestions = list.status === 200 ? suggestWorkflows(list.body?.workflows ?? []) : [];
403
+ 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(", ")}` : ""}`);
404
+ }
339
405
  workflow = String(chosen.id);
340
406
  workflowLabel = chosen.name;
341
407
  log(`Using the "${workflowLabel}" workflow (${chosen.path}), which looks like the main pull request CI. Pass --workflow to choose another.`);
@@ -382,7 +448,7 @@ export async function collectRedBuilds(options) {
382
448
  if (readable)
383
449
  jobs.set(run.id, list);
384
450
  }
385
- const checkJobs = red.flatMap((run) => (jobs.get(run.id) ?? []).filter((j) => (j.conclusion === "failure" || j.conclusion === "timed_out") && bucketJob(j, patterns) === "check"));
451
+ const checkJobs = red.flatMap((run) => (jobs.get(run.id) ?? []).filter((j) => (j.conclusion === "failure" || j.conclusion === "timed_out") && bucketJob(j, patterns, run.workflowName) === "check"));
386
452
  log(`Reading failure annotations of ${checkJobs.length} failing check jobs...`);
387
453
  for (const job of checkJobs) {
388
454
  const { status, body } = await get(`repos/${repository}/check-runs/${job.id}/annotations?per_page=50`);
@@ -416,7 +482,8 @@ export async function collectRedBuilds(options) {
416
482
  stoppedEarly = error.message;
417
483
  }
418
484
  }
419
- const report = summarise(repository, runs, rows, stoppedEarly);
485
+ const neverStarted = runs.filter((r) => r.conclusion === "failure" && jobs.has(r.id) && nothingRan(jobs.get(r.id))).length;
486
+ const report = summarise(repository, runs, rows, stoppedEarly, neverStarted);
420
487
  report.workflow = workflowLabel || runs[0]?.workflowName || null;
421
488
  return report;
422
489
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@diffci.com/diffci",
3
- "version": "0.3.43",
3
+ "version": "0.3.45",
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",