@diffci.com/diffci 0.2.8 → 0.2.10

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.
@@ -0,0 +1,50 @@
1
+ import { readFileSync } from "node:fs";
2
+ import { resolve } from "node:path";
3
+ function normalizeTarget(target) {
4
+ return target.trim();
5
+ }
6
+ export function detectSpecificationConflicts(specifications) {
7
+ const ids = new Set();
8
+ const owners = new Map();
9
+ for (const specification of specifications) {
10
+ if (!specification || typeof specification.id !== "string" || !specification.id.trim())
11
+ throw new Error("every specification requires a non-empty id");
12
+ const id = specification.id.trim();
13
+ if (ids.has(id))
14
+ throw new Error(`duplicate specification id: ${id}`);
15
+ ids.add(id);
16
+ const rawTargets = Array.isArray(specification.logicalTarget) ? specification.logicalTarget : [specification.logicalTarget];
17
+ if (!rawTargets.length || rawTargets.some((target) => typeof target !== "string" || !target.trim())) {
18
+ throw new Error(`specification ${id} requires at least one non-empty logicalTarget`);
19
+ }
20
+ for (const rawTarget of rawTargets) {
21
+ const target = normalizeTarget(rawTarget);
22
+ const targetOwners = owners.get(target) ?? new Set();
23
+ targetOwners.add(id);
24
+ owners.set(target, targetOwners);
25
+ }
26
+ }
27
+ const conflicts = [...owners.entries()]
28
+ .filter(([, targetOwners]) => targetOwners.size > 1)
29
+ .map(([logicalTarget, targetOwners]) => ({ logicalTarget, specificationIds: [...targetOwners].sort() }))
30
+ .sort((a, b) => a.logicalTarget.localeCompare(b.logicalTarget));
31
+ return {
32
+ schema: "diffci.specConflicts.v1",
33
+ valid: conflicts.length === 0,
34
+ specificationsChecked: specifications.length,
35
+ logicalTargetsChecked: owners.size,
36
+ conflicts,
37
+ blockers: conflicts.map((conflict) => `logical target "${conflict.logicalTarget}" is changed by specifications ${conflict.specificationIds.join(", ")}`),
38
+ };
39
+ }
40
+ export function readSpecificationFile(path) {
41
+ const parsed = JSON.parse(readFileSync(resolve(path), "utf8"));
42
+ const specifications = Array.isArray(parsed)
43
+ ? parsed
44
+ : parsed && typeof parsed === "object" && Array.isArray(parsed.specifications)
45
+ ? parsed.specifications
46
+ : undefined;
47
+ if (!specifications)
48
+ throw new Error("specification file must be an array or an object with a specifications array");
49
+ return specifications;
50
+ }
@@ -1,7 +1,9 @@
1
1
  import { execFileSync, spawnSync } from "node:child_process";
2
2
  import { createHash } from "node:crypto";
3
- import { mkdirSync, readFileSync, writeFileSync } from "node:fs";
4
- import { dirname, resolve } from "node:path";
3
+ import { existsSync, lstatSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
4
+ import { arch, cpus, platform, release, totalmem } from "node:os";
5
+ import { basename, dirname, resolve } from "node:path";
6
+ import { classifyFailureFromEvidence, computeFailureFingerprint } from "../preflight/fingerprint.js";
5
7
  function tail(value, bytes) {
6
8
  if (Buffer.byteLength(value, "utf8") <= bytes)
7
9
  return value;
@@ -32,20 +34,93 @@ function readSelectionFromObservation(path) {
32
34
  observerVersion: typeof parsed.observer?.version === "string" ? parsed.observer.version : undefined,
33
35
  };
34
36
  }
37
+ const DEPENDENCY_INPUT_NAMES = new Set([
38
+ "package.json", "package-lock.json", "npm-shrinkwrap.json", "pnpm-lock.yaml", "yarn.lock", "bun.lock", "bun.lockb",
39
+ "pom.xml", "settings.gradle", "settings.gradle.kts", "build.gradle", "build.gradle.kts", "gradle.lockfile",
40
+ "go.mod", "go.sum", "go.work", "go.work.sum", "cargo.toml", "cargo.lock", "pyproject.toml", "poetry.lock",
41
+ "pipfile", "pipfile.lock", "uv.lock", "gemfile", "gemfile.lock", "composer.json", "composer.lock",
42
+ ]);
43
+ const RESOLVED_DEPENDENCY_MARKERS = [
44
+ "node_modules/.package-lock.json",
45
+ "node_modules/.modules.yaml",
46
+ ".pnp.cjs",
47
+ ".pnp.data.json",
48
+ "vendor/composer/installed.json",
49
+ ];
50
+ function gitBuffer(cwd, args) {
51
+ try {
52
+ return execFileSync("git", args, { cwd, encoding: "buffer", stdio: ["ignore", "pipe", "ignore"], maxBuffer: 256 * 1024 * 1024 });
53
+ }
54
+ catch {
55
+ return undefined;
56
+ }
57
+ }
58
+ function nulPaths(buffer) {
59
+ if (!buffer)
60
+ return [];
61
+ return buffer.toString("utf8").split("\0").filter(Boolean);
62
+ }
63
+ function hashFiles(cwd, paths, seed = "") {
64
+ const hash = createHash("sha256").update(seed);
65
+ for (const path of [...new Set(paths)].sort()) {
66
+ hash.update("\0path\0").update(path);
67
+ const absolute = resolve(cwd, path);
68
+ try {
69
+ const stat = lstatSync(absolute);
70
+ hash.update(stat.isSymbolicLink() ? "symlink" : stat.isFile() ? "file" : "other");
71
+ if (stat.isFile() || stat.isSymbolicLink())
72
+ hash.update(readFileSync(absolute));
73
+ }
74
+ catch {
75
+ hash.update("missing");
76
+ }
77
+ }
78
+ return hash.digest("hex");
79
+ }
80
+ function dirtyContentDigest(cwd, status) {
81
+ const modified = nulPaths(gitBuffer(cwd, ["ls-files", "-m", "-o", "--exclude-standard", "-z"]));
82
+ const staged = nulPaths(gitBuffer(cwd, ["diff", "--cached", "--name-only", "-z"]));
83
+ return hashFiles(cwd, [...modified, ...staged], status);
84
+ }
85
+ function dependencyInputs(cwd) {
86
+ const listed = nulPaths(gitBuffer(cwd, ["ls-files", "-c", "-o", "--exclude-standard", "-z"]));
87
+ if (!listed.length)
88
+ return undefined;
89
+ const files = listed.filter((path) => {
90
+ if (path.split(/[\\/]/).includes("node_modules"))
91
+ return false;
92
+ const name = basename(path).toLowerCase();
93
+ return DEPENDENCY_INPUT_NAMES.has(name) || /^requirements(?:[-_.].+)?\.txt$/i.test(name);
94
+ }).sort();
95
+ return { files, sha256: hashFiles(cwd, files, "diffci-dependency-inputs-v1") };
96
+ }
97
+ function resolvedDependencyMarkers(cwd) {
98
+ const files = RESOLVED_DEPENDENCY_MARKERS.filter((path) => existsSync(resolve(cwd, path)));
99
+ return files.length ? { files, sha256: hashFiles(cwd, files, "diffci-resolved-dependencies-v1") } : undefined;
100
+ }
35
101
  function checkoutSnapshot(cwd) {
36
102
  const capturedAt = new Date().toISOString();
37
103
  try {
38
104
  const headSha = execFileSync("git", ["rev-parse", "HEAD"], { cwd, encoding: "utf8", stdio: ["ignore", "pipe", "ignore"] }).trim();
39
105
  const status = execFileSync("git", ["status", "--porcelain=v1", "-z", "--untracked-files=all"], { cwd, encoding: "buffer", stdio: ["ignore", "pipe", "ignore"] });
40
- return { capturedAt, headSha, worktreeDigest: createHash("sha256").update(status).digest("hex") };
106
+ const dependencies = dependencyInputs(cwd);
107
+ const resolved = resolvedDependencyMarkers(cwd);
108
+ return {
109
+ capturedAt,
110
+ headSha,
111
+ worktreeDigest: dirtyContentDigest(cwd, status),
112
+ dependencyInputsSha256: dependencies?.sha256,
113
+ dependencyInputFiles: dependencies?.files,
114
+ resolvedDependencySha256: resolved?.sha256,
115
+ resolvedDependencyFiles: resolved?.files,
116
+ };
41
117
  }
42
118
  catch {
43
119
  return { capturedAt };
44
120
  }
45
121
  }
46
- function buildProvenance(selection, beforeFull, afterFull, afterSelected) {
122
+ function buildProvenance(selection, beforeFull, afterFull, afterSelected, snapshots = [beforeFull, afterFull, afterSelected]) {
47
123
  const invalidReasons = [];
48
- const snapshots = [beforeFull, afterFull, afterSelected];
49
124
  const expectedHeadSha = selection.headSha ?? (selection.source === "manual" ? beforeFull.headSha : undefined);
50
125
  if (snapshots.some(snapshot => !snapshot.headSha || !snapshot.worktreeDigest))
51
126
  invalidReasons.push("checkout identity could not be captured for every execution boundary");
@@ -57,6 +132,13 @@ function buildProvenance(selection, beforeFull, afterFull, afterSelected) {
57
132
  invalidReasons.push("checkout HEAD changed during paired execution");
58
133
  if (new Set(snapshots.map(snapshot => snapshot.worktreeDigest)).size !== 1)
59
134
  invalidReasons.push("worktree changed during paired execution");
135
+ if (snapshots.some(snapshot => !snapshot.dependencyInputsSha256))
136
+ invalidReasons.push("dependency input identity could not be captured for every execution boundary");
137
+ if (new Set(snapshots.map(snapshot => snapshot.dependencyInputsSha256)).size !== 1)
138
+ invalidReasons.push("dependency manifests or lockfiles changed during paired execution");
139
+ const resolved = snapshots.map(snapshot => snapshot.resolvedDependencySha256);
140
+ if (resolved.some(Boolean) && (resolved.some(value => !value) || new Set(resolved).size !== 1))
141
+ invalidReasons.push("resolved dependency markers changed during paired execution");
60
142
  return {
61
143
  baseSha: selection.baseSha,
62
144
  headSha: expectedHeadSha,
@@ -65,6 +147,7 @@ function buildProvenance(selection, beforeFull, afterFull, afterSelected) {
65
147
  beforeFull,
66
148
  afterFull,
67
149
  afterSelected,
150
+ snapshots,
68
151
  checkoutStable: invalidReasons.length === 0,
69
152
  invalidReasons,
70
153
  };
@@ -78,6 +161,83 @@ function resolveSelection(options) {
78
161
  throw new Error("--selected <command> or --selected-from-report <path> is required");
79
162
  return { command: options.selected, source: "manual" };
80
163
  }
164
+ function captureRunnerIdentity(env = process.env) {
165
+ const identity = {
166
+ platform: platform(),
167
+ architecture: arch(),
168
+ osRelease: release(),
169
+ nodeVersion: process.version,
170
+ cpuModel: cpus()[0]?.model,
171
+ cpuCount: cpus().length,
172
+ totalMemoryBytes: totalmem(),
173
+ ci: env.GITHUB_ACTIONS === "true" ? "github-actions" : env.CI ? String(env.CI) : undefined,
174
+ runnerName: env.RUNNER_NAME,
175
+ runnerOs: env.RUNNER_OS,
176
+ runnerArch: env.RUNNER_ARCH,
177
+ runnerEnvironment: env.RUNNER_ENVIRONMENT,
178
+ imageOs: env.ImageOS,
179
+ imageVersion: env.ImageVersion,
180
+ };
181
+ return {
182
+ ...identity,
183
+ fingerprintSha256: createHash("sha256").update(JSON.stringify(identity)).digest("hex"),
184
+ };
185
+ }
186
+ function range(values) {
187
+ if (!values.length)
188
+ return { min: 0, median: 0, max: 0 };
189
+ const sorted = [...values].sort((a, b) => a - b);
190
+ const middle = Math.floor(sorted.length / 2);
191
+ const median = sorted.length % 2 ? sorted[middle] : (sorted[middle - 1] + sorted[middle]) / 2;
192
+ return { min: sorted[0], median, max: sorted[sorted.length - 1] };
193
+ }
194
+ function failureEvidence(measurement, arm, trial) {
195
+ if (measurement.exitCode === 0 && !measurement.timedOut)
196
+ return undefined;
197
+ const errorText = `${measurement.stderrTail}\n${measurement.stdoutTail}`.trim() || `exit ${String(measurement.exitCode)}`;
198
+ const failureClass = measurement.timedOut
199
+ ? "TIMEOUT"
200
+ : classifyFailureFromEvidence({ jobName: `verify-savings:${arm}`, command: measurement.command, errorText });
201
+ return {
202
+ arm,
203
+ trial,
204
+ failureClass,
205
+ // The arm is reported separately. Keep it out of the normalized fingerprint so
206
+ // an identical repository failure in both arms can be recognized as pre-existing.
207
+ fingerprint: computeFailureFingerprint({ failureClass, jobName: "verify-savings", errorText }),
208
+ };
209
+ }
210
+ function assessFailures(trials) {
211
+ const evidence = trials.flatMap((trial) => [
212
+ failureEvidence(trial.full, "full", trial.index),
213
+ failureEvidence(trial.selected, "selected", trial.index),
214
+ ]).filter((value) => value !== undefined);
215
+ if (!evidence.length)
216
+ return { kind: "none", confidence: "not-applicable", explanation: "Every measured arm passed.", evidence };
217
+ const fullPasses = trials.map((trial) => trial.full.exitCode === 0 && !trial.full.timedOut);
218
+ const selectedPasses = trials.map((trial) => trial.selected.exitCode === 0 && !trial.selected.timedOut);
219
+ const varying = (values) => new Set(values).size > 1;
220
+ if (varying(fullPasses) || varying(selectedPasses)) {
221
+ return { kind: "likely_flaky", confidence: trials.length >= 3 ? "medium" : "low", explanation: "At least one arm changed pass/fail outcome across repeated executions.", evidence };
222
+ }
223
+ if (evidence.some((item) => item.failureClass === "RUNNER_INFRASTRUCTURE" || item.failureClass === "TIMEOUT")) {
224
+ return { kind: "infrastructure", confidence: "medium", explanation: "Failure output matched a narrow timeout or runner-infrastructure signature.", evidence };
225
+ }
226
+ const fullFailures = evidence.filter((item) => item.arm === "full");
227
+ const selectedFailures = evidence.filter((item) => item.arm === "selected");
228
+ const stableFull = fullFailures.length === trials.length && new Set(fullFailures.map((item) => item.fingerprint)).size === 1;
229
+ const stableSelected = selectedFailures.length === trials.length && new Set(selectedFailures.map((item) => item.fingerprint)).size === 1;
230
+ if (stableFull && selectedFailures.length === 0) {
231
+ if (trials.length >= 3) {
232
+ return { kind: "selection_miss", confidence: "high", explanation: "The full arm reproduced the same failure in at least three trials while every selected arm passed. Inspect the omitted test before treating the selection as safe.", evidence };
233
+ }
234
+ return { kind: "inconclusive", confidence: "low", explanation: "The full arm failed while the selected arm passed, but fewer than three repetitions cannot separate a stable miss from a flake.", evidence };
235
+ }
236
+ if (stableFull && stableSelected && fullFailures[0]?.fingerprint === selectedFailures[0]?.fingerprint) {
237
+ return { kind: "pre_existing", confidence: trials.length >= 2 ? "medium" : "low", explanation: "Both arms reproduced the same normalized failure signature; it is shared rather than evidence of an omitted-test miss.", evidence };
238
+ }
239
+ return { kind: "inconclusive", confidence: "low", explanation: "The failures were not stable enough to classify conservatively.", evidence };
240
+ }
81
241
  export function measureCommand(command, options) {
82
242
  const startedAt = new Date().toISOString();
83
243
  const started = Date.now();
@@ -111,15 +271,47 @@ export function measureCommand(command, options) {
111
271
  };
112
272
  }
113
273
  export function buildVerifySavingsReport(input) {
274
+ const defaultProtocol = {
275
+ repetitions: 1,
276
+ alternatingOrder: false,
277
+ declaredCacheState: "unknown",
278
+ cacheStateControlled: false,
279
+ };
280
+ const protocol = input.protocol ?? defaultProtocol;
281
+ const provenance = input.provenance ?? {
282
+ beforeFull: { capturedAt: input.full.startedAt },
283
+ afterFull: { capturedAt: input.full.finishedAt },
284
+ afterSelected: { capturedAt: input.selected.finishedAt },
285
+ checkoutStable: false,
286
+ invalidReasons: ["checkout provenance was not captured"],
287
+ };
288
+ const trials = input.trials ?? [{
289
+ index: 1,
290
+ order: ["full", "selected"],
291
+ cacheState: { full: "unknown", selected: "potentially-warmed" },
292
+ preparations: [],
293
+ full: input.full,
294
+ selected: input.selected,
295
+ provenance,
296
+ }];
297
+ const fullRange = range(trials.map((trial) => trial.full.wallMs));
298
+ const selectedRange = range(trials.map((trial) => trial.selected.wallMs));
114
299
  const overhead = input.analysisOverheadMs ?? 0;
115
- const netSelectedMs = input.selected.wallMs + overhead;
116
- const deltaMs = input.full.wallMs - netSelectedMs;
117
- const grossPercentChange = input.full.wallMs > 0 ? ((input.full.wallMs - input.selected.wallMs) / input.full.wallMs) * 100 : 0;
118
- const percentChange = input.full.wallMs > 0 ? (deltaMs / input.full.wallMs) * 100 : 0;
119
- const fullCommandSucceeded = input.full.exitCode === 0 && !input.full.timedOut;
120
- const selectedCommandSucceeded = input.selected.exitCode === 0 && !input.selected.timedOut;
121
- const missedFailureSignal = !fullCommandSucceeded && selectedCommandSucceeded;
122
- const evidenceValid = fullCommandSucceeded && selectedCommandSucceeded && (input.provenance?.checkoutStable ?? false);
300
+ const netSelectedMs = selectedRange.median + overhead;
301
+ const deltaMs = fullRange.median - netSelectedMs;
302
+ const grossPercentChange = fullRange.median > 0 ? ((fullRange.median - selectedRange.median) / fullRange.median) * 100 : 0;
303
+ const percentChange = fullRange.median > 0 ? (deltaMs / fullRange.median) * 100 : 0;
304
+ const fullCommandSucceeded = trials.every((trial) => trial.full.exitCode === 0 && !trial.full.timedOut);
305
+ const selectedCommandSucceeded = trials.every((trial) => trial.selected.exitCode === 0 && !trial.selected.timedOut);
306
+ const missedFailureSignal = trials.some((trial) => (trial.full.exitCode !== 0 || trial.full.timedOut) && trial.selected.exitCode === 0 && !trial.selected.timedOut);
307
+ const preparationsSucceeded = trials.every((trial) => trial.preparations.every((preparation) => preparation.exitCode === 0 && !preparation.timedOut));
308
+ const evidenceValid = fullCommandSucceeded && selectedCommandSucceeded && provenance.checkoutStable && preparationsSucceeded;
309
+ const performanceEvidence = !evidenceValid
310
+ ? "INVALID"
311
+ : protocol.repetitions >= 3 && protocol.alternatingOrder && protocol.cacheStateControlled
312
+ ? "CONTROLLED"
313
+ : "PRELIMINARY";
314
+ const failureAssessment = input.failureAssessment ?? assessFailures(trials);
123
315
  const notes = [
124
316
  "This is paired runtime evidence, not a production-savings claim.",
125
317
  "Full and selected commands were run sequentially in the same checkout.",
@@ -127,12 +319,15 @@ export function buildVerifySavingsReport(input) {
127
319
  ? "No analysis overhead was provided, so net selected runtime equals selected command runtime."
128
320
  : "Net selected runtime includes DiffCI analysis overhead.",
129
321
  ];
322
+ notes.push(performanceEvidence === "CONTROLLED"
323
+ ? "Runtime evidence used at least three alternating, cache-prepared repetitions."
324
+ : "Runtime evidence is preliminary until at least three alternating, cache-prepared repetitions agree.");
130
325
  if (missedFailureSignal)
131
326
  notes.push("Full failed while selected passed; inspect outputs before treating the selection as safe.");
132
327
  if (input.provenance && !input.provenance.checkoutStable)
133
328
  notes.push(`Checkout provenance invalid: ${input.provenance.invalidReasons.join("; ")}.`);
134
329
  return {
135
- schema: "diffci.verifySavings.v2",
330
+ schema: "diffci.verifySavings.v3",
136
331
  producedAt: input.producedAt ?? new Date().toISOString(),
137
332
  label: input.label,
138
333
  cwd: input.cwd,
@@ -142,18 +337,16 @@ export function buildVerifySavingsReport(input) {
142
337
  observationReportPath: input.selection.observationReportPath,
143
338
  selectedTestCount: input.selection.selectedTestCount,
144
339
  totalTestCount: input.selection.totalTestCount,
145
- provenance: input.provenance ?? {
146
- beforeFull: { capturedAt: input.full.startedAt },
147
- afterFull: { capturedAt: input.full.finishedAt },
148
- afterSelected: { capturedAt: input.selected.finishedAt },
149
- checkoutStable: false,
150
- invalidReasons: ["checkout provenance was not captured"],
151
- },
340
+ provenance,
341
+ runnerIdentity: input.runnerIdentity ?? captureRunnerIdentity(),
342
+ protocol,
343
+ trials,
344
+ failureAssessment,
152
345
  full: input.full,
153
346
  selected: input.selected,
154
347
  comparison: {
155
- fullWallMs: input.full.wallMs,
156
- selectedWallMs: input.selected.wallMs,
348
+ fullWallMs: fullRange.median,
349
+ selectedWallMs: selectedRange.median,
157
350
  netSelectedMs,
158
351
  deltaMs,
159
352
  grossPercentChange,
@@ -162,6 +355,10 @@ export function buildVerifySavingsReport(input) {
162
355
  fullCommandSucceeded,
163
356
  missedFailureSignal,
164
357
  evidenceValid,
358
+ performanceEvidence,
359
+ repetitions: trials.length,
360
+ fullWallMsRange: fullRange,
361
+ selectedWallMsRange: selectedRange,
165
362
  },
166
363
  notes,
167
364
  };
@@ -195,7 +392,9 @@ export function renderVerifySavingsMarkdown(report) {
195
392
  ? "Inspect the failed command output and rerun before treating this as savings evidence."
196
393
  : !report.comparison.evidenceValid
197
394
  ? "Fix the checkout/provenance issue and rerun before treating this as savings evidence."
198
- : "Repeat on the intended runner with controlled cache state before making a production-savings claim.";
395
+ : report.comparison.performanceEvidence === "CONTROLLED"
396
+ ? "Review the repeated-run distribution and failure assessment before considering a production trial."
397
+ : "Repeat at least three times with alternating order and a cache-preparation command to establish controlled cache state before making a production-savings claim.";
199
398
  return `${title}
200
399
 
201
400
  Produced at: ${report.producedAt}
@@ -217,6 +416,27 @@ ${!report.comparison.fullCommandSucceeded || !report.comparison.selectedCommandS
217
416
  | Net selected runtime | ${formatMs(report.comparison.netSelectedMs)} |
218
417
  | Delta vs full | ${formatMs(report.comparison.deltaMs)} ${deltaLabel} |
219
418
  | Percent change vs full | ${formatPercent(report.comparison.percentChange)} |
419
+ | Runtime evidence | ${report.comparison.performanceEvidence.toLowerCase()} |
420
+ | Repetitions | ${report.comparison.repetitions} |
421
+ | Full runtime range | ${formatMs(report.comparison.fullWallMsRange.min)} / ${formatMs(report.comparison.fullWallMsRange.median)} / ${formatMs(report.comparison.fullWallMsRange.max)} (min/median/max) |
422
+ | Selected runtime range | ${formatMs(report.comparison.selectedWallMsRange.min)} / ${formatMs(report.comparison.selectedWallMsRange.median)} / ${formatMs(report.comparison.selectedWallMsRange.max)} (min/median/max) |
423
+
424
+ ## Measurement Protocol
425
+
426
+ | Field | Value |
427
+ | --- | --- |
428
+ | Alternating arm order | ${report.protocol.alternatingOrder ? "yes" : "no"} |
429
+ | Declared cache state | ${report.protocol.declaredCacheState} |
430
+ | Cache preparation command | ${report.protocol.cachePreparationCommand ? `\`${report.protocol.cachePreparationCommand.replaceAll("|", "\\|")}\`` : "not provided"} |
431
+ | Cache state controlled | ${report.protocol.cacheStateControlled ? "yes" : "no"} |
432
+
433
+ ## Failure Assessment
434
+
435
+ | Field | Value |
436
+ | --- | --- |
437
+ | Classification | ${report.failureAssessment.kind} |
438
+ | Confidence | ${report.failureAssessment.confidence} |
439
+ | Explanation | ${report.failureAssessment.explanation} |
220
440
 
221
441
  ## Provenance
222
442
 
@@ -227,6 +447,9 @@ ${!report.comparison.fullCommandSucceeded || !report.comparison.selectedCommandS
227
447
  | Observation SHA-256 | \`${report.provenance.observationSha256 ?? "unavailable"}\` |
228
448
  | DiffCI observer version | ${report.provenance.observerVersion ?? "unavailable"} |
229
449
  | Checkout stable across both arms | ${report.provenance.checkoutStable ? "yes" : "no"} |
450
+ | Dependency inputs SHA-256 | \`${report.provenance.beforeFull.dependencyInputsSha256 ?? "unavailable"}\` |
451
+ | Resolved dependency markers SHA-256 | \`${report.provenance.beforeFull.resolvedDependencySha256 ?? "unavailable"}\` |
452
+ | Runner identity SHA-256 | \`${report.runnerIdentity.fingerprintSha256}\` |
230
453
 
231
454
  ## Commands
232
455
 
@@ -240,7 +463,7 @@ ${!report.comparison.fullCommandSucceeded || !report.comparison.selectedCommandS
240
463
  | Question | Answer |
241
464
  | --- | --- |
242
465
  | Command coverage | ${commandCoverage} |
243
- | Cache state | Not controlled by this one report; repeat with documented warm/cold cache conditions before claiming savings. |
466
+ | Cache state | ${report.protocol.cacheStateControlled ? `${report.protocol.declaredCacheState}; reset/preparation applied before each arm.` : `${report.protocol.declaredCacheState}; not independently controlled.`} |
244
467
  | Invalid evidence handling | Failed commands or unstable checkout provenance are labelled diagnostic only above. |
245
468
  | Next step | ${nextStep} |
246
469
 
@@ -256,21 +479,73 @@ function writeText(path, value) {
256
479
  export function runVerifySavings(options) {
257
480
  const selection = resolveSelection(options);
258
481
  const analysisOverheadMs = options.analysisOverheadMs ?? selection.analysisOverheadMs;
259
- const beforeFull = checkoutSnapshot(options.cwd);
260
- const full = measureCommand(options.full, options);
261
- const afterFull = checkoutSnapshot(options.cwd);
262
- const selected = measureCommand(selection.command, options);
263
- const afterSelected = checkoutSnapshot(options.cwd);
264
- const provenance = buildProvenance(selection, beforeFull, afterFull, afterSelected);
482
+ const repetitions = options.repetitions ?? 1;
483
+ if (!Number.isInteger(repetitions) || repetitions < 1 || repetitions > 20)
484
+ throw new Error("--repetitions must be an integer from 1 to 20");
485
+ const declaredCacheState = options.cacheState ?? "unknown";
486
+ if (!["cold", "warm", "unknown"].includes(declaredCacheState))
487
+ throw new Error("--cache-state must be cold, warm, or unknown");
488
+ const alternatingOrder = options.alternateOrder ?? repetitions > 1;
489
+ const protocol = {
490
+ repetitions,
491
+ alternatingOrder,
492
+ declaredCacheState,
493
+ cachePreparationCommand: options.cachePreparationCommand,
494
+ cacheStateControlled: declaredCacheState !== "unknown" && Boolean(options.cachePreparationCommand),
495
+ };
496
+ const trials = [];
497
+ for (let index = 0; index < repetitions; index++) {
498
+ const order = alternatingOrder && index % 2 === 1 ? ["selected", "full"] : ["full", "selected"];
499
+ const preparations = [];
500
+ const measurements = {};
501
+ const snapshots = [];
502
+ for (const arm of order) {
503
+ if (options.cachePreparationCommand)
504
+ preparations.push(measureCommand(options.cachePreparationCommand, options));
505
+ snapshots.push(checkoutSnapshot(options.cwd));
506
+ measurements[arm] = measureCommand(arm === "full" ? options.full : selection.command, options);
507
+ snapshots.push(checkoutSnapshot(options.cwd));
508
+ }
509
+ const full = measurements.full;
510
+ const selected = measurements.selected;
511
+ const beforeFull = order[0] === "full" ? snapshots[0] : snapshots[2];
512
+ const afterFull = order[0] === "full" ? snapshots[1] : snapshots[3];
513
+ const afterSelected = order[0] === "selected" ? snapshots[1] : snapshots[3];
514
+ const provenance = buildProvenance(selection, beforeFull, afterFull, afterSelected, snapshots);
515
+ const firstState = declaredCacheState;
516
+ const secondState = options.cachePreparationCommand
517
+ ? declaredCacheState
518
+ : declaredCacheState === "warm"
519
+ ? "warm"
520
+ : "potentially-warmed";
521
+ trials.push({
522
+ index: index + 1,
523
+ order,
524
+ cacheState: order[0] === "full"
525
+ ? { full: firstState, selected: secondState }
526
+ : { selected: firstState, full: secondState },
527
+ preparations,
528
+ full,
529
+ selected,
530
+ provenance,
531
+ });
532
+ }
533
+ const first = trials[0];
534
+ const allSnapshots = trials.flatMap((trial) => trial.provenance.snapshots ?? []);
535
+ const provenance = buildProvenance(selection, first.provenance.beforeFull, first.provenance.afterFull, first.provenance.afterSelected, allSnapshots);
265
536
  return buildVerifySavingsReport({
266
537
  label: options.label,
267
538
  cwd: options.cwd,
268
539
  timeoutMs: options.timeoutMs,
269
540
  analysisOverheadMs,
270
541
  selection,
271
- full,
272
- selected,
542
+ full: first.full,
543
+ selected: first.selected,
273
544
  provenance,
545
+ runnerIdentity: captureRunnerIdentity(),
546
+ protocol,
547
+ trials,
548
+ failureAssessment: assessFailures(trials),
274
549
  });
275
550
  }
276
551
  export function writeVerifySavingsReport(report, paths) {
@@ -281,16 +556,18 @@ export function writeVerifySavingsReport(report, paths) {
281
556
  export function formatVerifySavingsSummary(report) {
282
557
  if (!report.comparison.fullCommandSucceeded || !report.comparison.selectedCommandSucceeded) {
283
558
  return "DiffCI verify-savings: comparison invalid because one or both commands failed" +
559
+ `\n failure assessment: ${report.failureAssessment.kind} (${report.failureAssessment.confidence}) - ${report.failureAssessment.explanation}` +
284
560
  (report.comparison.missedFailureSignal ? "\n warning: full failed while selected passed; inspect outputs before claiming safety" : "");
285
561
  }
286
562
  if (!report.comparison.evidenceValid) {
287
563
  return `DiffCI verify-savings: comparison invalid because checkout provenance failed\n ${report.provenance.invalidReasons.join("; ")}`;
288
564
  }
289
565
  const lines = [
290
- `DiffCI verify-savings: test execution ${Math.abs(report.comparison.grossPercentChange).toFixed(1)}% ${report.comparison.grossPercentChange >= 0 ? "faster" : "slower"} in this paired run`,
566
+ `DiffCI verify-savings: ${report.comparison.performanceEvidence === "CONTROLLED" ? "controlled repeated" : "preliminary"} test execution ${Math.abs(report.comparison.grossPercentChange).toFixed(1)}% ${report.comparison.grossPercentChange >= 0 ? "faster" : "slower"} (${report.comparison.repetitions} ${report.comparison.repetitions === 1 ? "trial" : "trials"})`,
291
567
  ` full: ${formatMs(report.comparison.fullWallMs)}`,
292
568
  ` selected: ${formatMs(report.comparison.selectedWallMs)} + analysis ${formatMs(report.analysisOverheadMs ?? 0)} = ${formatMs(report.comparison.netSelectedMs)}`,
293
569
  ` net including analysis: ${Math.abs(report.comparison.percentChange).toFixed(1)}% ${report.comparison.deltaMs >= 0 ? "faster" : "slower"} (${formatMs(Math.abs(report.comparison.deltaMs))} ${report.comparison.deltaMs >= 0 ? "saved" : "added"})`,
570
+ ` cache: ${report.protocol.declaredCacheState}${report.protocol.cacheStateControlled ? " (prepared before each arm)" : " (not controlled)"}`,
294
571
  ];
295
572
  if (report.comparison.missedFailureSignal) {
296
573
  lines.push(" warning: full failed while selected passed; inspect outputs before claiming safety");
@@ -0,0 +1,61 @@
1
+ // Ordered most-specific-first. A pattern here is real error-message vocabulary observed in this
2
+ // project's own actual CI failures (see docs/research/2026-08-22-preflight-p0-historical-failure-study.md
3
+ // case studies) or well-known tool output, not invented from memory.
4
+ const CLASSIFICATION_RULES = [
5
+ { failureClass: "TIMEOUT", patterns: [/timed? ?out/i, /exceeded the timeout/i, /context deadline exceeded/i] },
6
+ { failureClass: "RUNNER_INFRASTRUCTURE", patterns: [/runner has received a shutdown signal/i, /lost communication with the server/i, /econnreset/i, /the job was canceled because/i, /no space left on device/i, /1101\b/i, /container (start|start collision)/i] },
7
+ { failureClass: "CONFIGURATION", patterns: [/ERR_UNKNOWN_BUILTIN_MODULE/i, /environment variable .* is not set/i, /missing required secret/i, /invalid configuration/i, /engines\.node/i, /unsupported engine/i] },
8
+ { failureClass: "DEPENDENCY", patterns: [/npm error (?:code )?(?:E404|ERESOLVE|EAI_AGAIN)/i, /could not resolve host/i, /module not found/i, /cannot find module/i, /peer dep(?:endency)? (?:conflict|missing)/i] },
9
+ { failureClass: "TYPECHECK", patterns: [/error TS\d{4}/i, /tsc --noEmit/i] },
10
+ { failureClass: "LINT", patterns: [/eslint/i, /\d+ problems? \(\d+ errors?/i] },
11
+ { failureClass: "BUILD", patterns: [/build failed/i, /compilation failed/i, /webpack (?:compiled with|failed)/i] },
12
+ { failureClass: "GENERATED_ARTIFACT", patterns: [/generated file(?:s)? (?:is|are) out of date/i, /diff detected in generated/i, /snapshot mismatch/i] },
13
+ { failureClass: "SECURITY_SCAN", patterns: [/codeql/i, /security alert/i, /vulnerability found/i] },
14
+ { failureClass: "DEPLOYMENT", patterns: [/deploy(?:ment)? failed/i, /wrangler deploy.*error/i, /rollout failed/i] },
15
+ { failureClass: "INTEGRATION_TEST", patterns: [/integration test/i] },
16
+ { failureClass: "UNIT_TEST", patterns: [/ERR_TEST_FAILURE/i, /not ok \d+/i, /AssertionError/i, /expected .* to (?:equal|be)/i] },
17
+ ];
18
+ export function classifyFailureFromEvidence(evidence) {
19
+ const haystack = `${evidence.command ?? ""} ${evidence.errorText}`;
20
+ for (const rule of CLASSIFICATION_RULES) {
21
+ if (rule.patterns.some((p) => p.test(haystack)))
22
+ return rule.failureClass;
23
+ }
24
+ return "UNKNOWN";
25
+ }
26
+ /**
27
+ * Normalizes volatile, incidental details out of an error message before fingerprinting (Part 3):
28
+ * - absolute filesystem paths -> a repo-relative-shaped placeholder
29
+ * - line:column numbers -> stripped (the same logical error at a slightly different line is still the
30
+ * same failure family)
31
+ * - hex hashes/ids (commit SHAs, container ids, uuids) -> stripped
32
+ * - ISO timestamps and other digit runs that look like durations/ids -> stripped
33
+ */
34
+ function normalizeErrorText(text) {
35
+ return text
36
+ .replace(/\/[\w./-]+(?:\.tsx?|\.jsx?|\.mjs|\.cjs)/g, "<path>")
37
+ .replace(/:\d+:\d+/g, "") // line:column
38
+ .replace(/\b[0-9a-f]{7,40}\b/gi, "<hash>")
39
+ .replace(/\b\d{4}-\d{2}-\d{2}T[\d:.]+Z?\b/g, "<timestamp>")
40
+ .replace(/\b\d+ms\b|\b\d+(?:\.\d+)?s\b/g, "<duration>")
41
+ .replace(/\b\d+\.\d+\b/g, "<duration>") // bare decimals (e.g. "duration_ms: 301.23") - almost always an incidental measurement, not part of the error's identity
42
+ .replace(/\s+/g, " ")
43
+ .trim()
44
+ .toLowerCase();
45
+ }
46
+ /**
47
+ * failure_fingerprint (Part 3): failureClass + job/step class + a normalized error signature + (when
48
+ * known) the specific failing test/module identifier - deliberately NOT the raw log. Two occurrences of
49
+ * "the same" failure (identical error class, same test, same normalized message) produce the identical
50
+ * fingerprint even if timestamps/paths/durations differ between the two CI runs.
51
+ */
52
+ export function computeFailureFingerprint(input) {
53
+ const parts = [
54
+ input.failureClass,
55
+ input.jobName.toLowerCase().trim(),
56
+ input.stepName?.toLowerCase().trim() ?? "",
57
+ input.failingTest?.toLowerCase().trim() ?? "",
58
+ normalizeErrorText(input.errorText).slice(0, 200), // bounded - a fingerprint is an identity key, not a log excerpt
59
+ ];
60
+ return parts.join("|");
61
+ }
@@ -0,0 +1,7 @@
1
+ export const FAILURE_CLASSES = [
2
+ "TYPECHECK", "LINT", "BUILD", "UNIT_TEST", "INTEGRATION_TEST", "DEPENDENCY", "CONFIGURATION",
3
+ "GENERATED_ARTIFACT", "SECURITY_SCAN", "DEPLOYMENT", "RUNNER_INFRASTRUCTURE", "TIMEOUT", "FLAKY", "UNKNOWN",
4
+ ];
5
+ export function isFailureClass(value) {
6
+ return FAILURE_CLASSES.includes(value);
7
+ }