@diffci.com/diffci 0.3.41 → 0.3.42

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1063,7 +1063,11 @@ function runVerifyWorkflow(flags, env) {
1063
1063
  }
1064
1064
  console.log(`Scanned ${result.workflowsScanned.length} workflow file(s).`);
1065
1065
  if (result.observerJobs.length === 0) {
1066
- console.log("No job runs the DiffCI action. Add one before starting the observation window.");
1066
+ // Jobs that run DiffCI as a gate (verify, check-run, fail-on-error) are allowed to fail and are not
1067
+ // observers, but their warnings still belong in front of the user rather than behind this return.
1068
+ for (const finding of result.findings)
1069
+ console.log(formatFinding(finding));
1070
+ console.log("No job runs DiffCI as an observer (jobs that run it as a gate, with verify, check-run or fail-on-error, are allowed to fail and are not checked here). Add an observer job before starting the observation window.");
1067
1071
  return 1;
1068
1072
  }
1069
1073
  console.log(`DiffCI runs in: ${result.observerJobs.join(", ")}`);
@@ -105,6 +105,16 @@ export declare function githubClient(token: string, options?: {
105
105
  fetchFn?: typeof fetch;
106
106
  sleep?: (ms: number) => Promise<void>;
107
107
  }): GitHubGet;
108
+ /**
109
+ * The main pull request CI among one sample page of runs: wall-clock minutes per workflow, doubled when
110
+ * its name or file looks like CI and cut to 5% when it looks like a scanner, preview, benchmark or bot.
111
+ * Plain "most minutes" picked SonarQube, Benchmarks and preview builds on real repositories.
112
+ */
113
+ export declare function pickMainWorkflow(sample: any[]): {
114
+ id: number;
115
+ name: string;
116
+ path: string;
117
+ } | undefined;
108
118
  export interface CollectOptions {
109
119
  repository: string;
110
120
  get: GitHubGet;
@@ -260,9 +260,19 @@ export function githubClient(token, options = {}) {
260
260
  if (wait > 0)
261
261
  await sleep(wait);
262
262
  last = Date.now();
263
- const res = await fetchFn(`https://api.github.com/${path}`, {
263
+ const request = () => fetchFn(`https://api.github.com/${path}`, {
264
264
  headers: { Accept: "application/vnd.github+json", Authorization: `Bearer ${token}`, "User-Agent": "diffci-red-builds", "X-GitHub-Api-Version": "2022-11-28" },
265
265
  });
266
+ let res;
267
+ try {
268
+ res = await request();
269
+ }
270
+ catch {
271
+ // A dropped connection ("fetch failed"), not a GitHub answer: one slow retry, then give up.
272
+ await sleep(10_000);
273
+ last = Date.now();
274
+ res = await request();
275
+ }
266
276
  if (res.headers.get("retry-after"))
267
277
  throw new StopCollection(`GitHub asked to slow down (Retry-After on ${path.split("?")[0]})`);
268
278
  const remaining = Number(res.headers.get("x-ratelimit-remaining") ?? "Infinity");
@@ -276,6 +286,33 @@ export function githubClient(token, options = {}) {
276
286
  return { status: res.status, body };
277
287
  };
278
288
  }
289
+ /** Workflows that run on pull requests but are not the test CI: scanners, previews, benchmarks, bots. */
290
+ const NOT_MAIN_WORKFLOW = /\b(preview|codeql|security|semgrep|sonar(qube|cloud)?|snyk|scorecard|bench(mark)?s?|size|label(er|s)?|stale|triage|greet(ings?)?|welcome|translations?|i18n|docs?|documentation|docker|image|deploy(ment)?|release|licen[cs]e|title|conventional|commits?|semantic|submodule|e2e|playwright|cypress|lighthouse|dependabot|renovate|cla|dco|changeset|storybook|chromatic)\b/i;
291
+ /** Names and file names the main pull request CI usually has. */
292
+ const MAIN_WORKFLOW = /\b(ci|cd|tests?|pipeline|pr|pull[-_ ]request|build|checks?|main|verify|validate|unit|lint|quality)\b/i;
293
+ /**
294
+ * The main pull request CI among one sample page of runs: wall-clock minutes per workflow, doubled when
295
+ * its name or file looks like CI and cut to 5% when it looks like a scanner, preview, benchmark or bot.
296
+ * Plain "most minutes" picked SonarQube, Benchmarks and preview builds on real repositories.
297
+ */
298
+ export function pickMainWorkflow(sample) {
299
+ const weight = new Map();
300
+ for (const r of sample) {
301
+ const span = (Date.parse(r.updated_at) - Date.parse(r.run_started_at ?? r.created_at)) / 60_000;
302
+ const path = String(r.path ?? "").replace(/^\.github\/workflows\//, "");
303
+ const entry = weight.get(r.workflow_id) ?? { name: String(r.name ?? r.workflow_id), path, minutes: 0 };
304
+ entry.minutes += Number.isFinite(span) && span > 0 ? span : 0;
305
+ weight.set(r.workflow_id, entry);
306
+ }
307
+ let best;
308
+ for (const [id, w] of weight) {
309
+ const text = `${w.name} ${w.path.replace(/\.ya?ml$/, "").replace(/[-_.]/g, " ")}`;
310
+ const score = (w.minutes + 0.01) * (NOT_MAIN_WORKFLOW.test(text) ? 0.05 : 1) * (MAIN_WORKFLOW.test(text) ? 2 : 1);
311
+ if (!best || score > best.score)
312
+ best = { id, name: w.name, path: w.path, score };
313
+ }
314
+ return best && { id: best.id, name: best.name, path: best.path };
315
+ }
279
316
  /** Fetches runs, jobs, annotations and commit messages, then classifies. Partial data on a stop. */
280
317
  export async function collectRedBuilds(options) {
281
318
  const { repository, get } = options;
@@ -296,19 +333,12 @@ export async function collectRedBuilds(options) {
296
333
  throw new Error(`${repository} not found, or its Actions history is not visible to this token`);
297
334
  if (status !== 200)
298
335
  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)
336
+ const chosen = pickMainWorkflow(body?.workflow_runs ?? []);
337
+ if (!chosen)
308
338
  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.`);
339
+ workflow = String(chosen.id);
340
+ workflowLabel = chosen.name;
341
+ log(`Using the "${workflowLabel}" workflow (${chosen.path}), which looks like the main pull request CI. Pass --workflow to choose another.`);
312
342
  }
313
343
  const base = `repos/${repository}/actions/workflows/${encodeURIComponent(workflow)}/runs`;
314
344
  for (let page = 1; runs.length < options.maxRuns; page++) {
@@ -111,14 +111,31 @@ function runInvokesDiffCiVerification(run) {
111
111
  * `./packages/diffci-cli/package.json`, and `check` reported both of those jobs as badly installed
112
112
  * observers. An echo line with a substitution, pipe or command separator is kept, because it can run
113
113
  * something.
114
+ *
115
+ * Three more (2026-11-13), all from Core's own release workflow, which `check` on Core reported as
116
+ * seven BLOCKING findings in jobs that publish DiffCI rather than run it:
117
+ * - scp-style Git remotes (`git@gitlab.com:diffci/diffci.git`), which are addresses like URLs;
118
+ * - plain `git` lines (`git commit -m "DiffCI components …"`, `git config user.name "DiffCI release"`),
119
+ * whose arguments are names, messages and refs. As with echo, a line with a substitution, pipe or
120
+ * command separator is kept;
121
+ * - the package spec of `npm view`/`info`/`show`, which reads registry metadata and never runs the
122
+ * package. `version=$(npm view @diffci.com/diffci@latest version)` resolves a version to pin.
114
123
  */
115
124
  function commandText(run) {
116
125
  return run
117
126
  .split("\n")
118
- .map((line) => line.replace(/(^|\s)#.*$/, "$1").replace(/[a-z][a-z0-9+.-]*:\/\/\S+/gi, " "))
119
- .map((line) => (/^\s*(?:echo|printf)\s/.test(line) && !/\$\(|`|\||&&|;/.test(line) ? "" : line))
120
127
  .map((line) => line
121
- .replace(/(^|\s)(?:-[fF]|--(?:raw-)?field)\s+(?:"[^"]*"|'[^']*'|\S+)/g, "$1")
128
+ .replace(/(^|\s)#.*$/, "$1")
129
+ .replace(/[a-z][a-z0-9+.-]*:\/\/\S+/gi, " ")
130
+ .replace(/\b[\w.-]+@[\w-]+(?:\.[\w-]+)+:[^\s"']+/g, " ")
131
+ .replace(/\bnpm(?:\.cmd)?\s+(?:view|info|show)\s+["']?[^\s"')]+["']?/g, "npm view "))
132
+ // Separators inside quotes are message text ("…/diffci; enable its write access"), so only
133
+ // unquoted ones count. A substitution counts anywhere, because double quotes still run it.
134
+ .map((line) => (/^\s*(?:echo|printf|git)\s/.test(line) && !/\$\(|`/.test(line) &&
135
+ !/\||&&|;/.test(line.replace(/"[^"]*"|'[^']*'/g, "")) ? "" : line))
136
+ .map((line) => line
137
+ // A field value may be quoted from its middle: `-f message="Release DiffCI …"`.
138
+ .replace(/(^|\s)(?:-[fF]|--(?:raw-)?field)\s+(?:(?:[^\s"']*(?:"[^"]*"|'[^']*'))+[^\s"']*|\S+)/g, "$1")
122
139
  .replace(/(^|[\s"'])repos\/[^\s"']+/g, "$1")
123
140
  .replace(/\$?\{?\b[A-Z][A-Z0-9]*_[A-Z0-9_]+\b\}?/g, " ")
124
141
  .replace(/[^\s"'()]*\.json\b/g, " "))
@@ -165,6 +182,12 @@ function referencesDiffCi(uses, repoPath, actionPattern) {
165
182
  }
166
183
  return false;
167
184
  }
185
+ /** Action inputs that deliberately let the DiffCI step decide its own job's outcome. */
186
+ const ACTION_GATE_INPUTS = ["verify", "check-run", "fail-on-error"];
187
+ function actionGateInputs(step) {
188
+ const inputs = isRecord(step.with) ? step.with : {};
189
+ return ACTION_GATE_INPUTS.filter((name) => inputs[name] === true || String(inputs[name]).trim().toLowerCase() === "true");
190
+ }
168
191
  function isPinnedToSha(uses) {
169
192
  const at = uses.lastIndexOf("@");
170
193
  if (at === -1)
@@ -201,9 +224,24 @@ export function auditWorkflows(repoPath, options = {}) {
201
224
  const steps = asArray(rawJob.steps).filter(isRecord);
202
225
  const isDiffCiStep = (step) => (typeof step.uses === "string" && referencesDiffCi(step.uses, repoPath, actionPattern)) ||
203
226
  (typeof step.run === "string" && runReferencesDiffCi(step.run, actionPattern));
204
- const isVerificationStep = (step) => typeof step.run === "string" && runInvokesDiffCiVerification(step.run);
227
+ const isVerificationStep = (step) => (typeof step.run === "string" && runInvokesDiffCiVerification(step.run)) ||
228
+ (typeof step.uses === "string" && isDiffCiStep(step) && actionGateInputs(step).length > 0);
205
229
  // This guard proves that observation jobs are inert. A dedicated fail-closed verification job
206
230
  // is a different product surface: making its own status check fail is its intended contract.
231
+ // The Action reaches the same surface through inputs: `verify` (the fast check), `check-run`
232
+ // (the merge gate) and `fail-on-error`. Before 2026-11-13 only the `run:` form was recognised,
233
+ // so every repository that turned on the 0.3.41 merge gate was told its installation was broken.
234
+ for (const step of steps) {
235
+ if (typeof step.uses === "string" && isDiffCiStep(step) && actionGateInputs(step).includes("fail-on-error")) {
236
+ findings.push({
237
+ severity: "WARNING",
238
+ code: "ACTION_FAILS_ON_ERROR",
239
+ message: `job "${jobId}" sets fail-on-error: "true", so a DiffCI refusal or error fails this job. That is meant for debugging an installation or testing the Action; turn it off for observation.`,
240
+ workflow: relativePath,
241
+ job: jobId,
242
+ });
243
+ }
244
+ }
207
245
  const diffciSteps = steps.filter((step) => isDiffCiStep(step) && !isVerificationStep(step));
208
246
  if (diffciSteps.length === 0)
209
247
  continue;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@diffci.com/diffci",
3
- "version": "0.3.41",
3
+ "version": "0.3.42",
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",