flakefinder 1.2.0 → 1.2.1

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.
Files changed (3) hide show
  1. package/README.md +32 -57
  2. package/dist/cli.js +1709 -1239
  3. package/package.json +7 -1
package/dist/cli.js CHANGED
@@ -4,1198 +4,1297 @@
4
4
  import { spawnSync as spawnSync4 } from "child_process";
5
5
  import { randomUUID as randomUUID2 } from "crypto";
6
6
  import {
7
- existsSync as existsSync6,
8
- mkdirSync as mkdirSync2,
9
- readFileSync as readFileSync7,
10
- realpathSync as realpathSync2,
7
+ existsSync as existsSync7,
8
+ mkdirSync as mkdirSync3,
9
+ readdirSync as readdirSync2,
10
+ readFileSync as readFileSync8,
11
+ realpathSync as realpathSync3,
12
+ rmSync as rmSync4,
11
13
  statSync as statSync7,
12
- writeFileSync as writeFileSync4
14
+ writeFileSync as writeFileSync5
13
15
  } from "fs";
14
- import path8 from "path";
16
+ import path11 from "path";
15
17
  import { Command } from "commander";
16
18
 
17
- // src/action/diff.ts
18
- var FLAKY = /* @__PURE__ */ new Set(["flaky-confirmed", "flaky-retry", "flaky-suspected"]);
19
- function computeNewFlakes(current, previous) {
20
- const prevFlaky = new Set(
21
- (previous ?? []).filter((v) => FLAKY.has(v.classification)).map((v) => v.testId)
22
- );
23
- return current.filter((v) => FLAKY.has(v.classification) && !prevFlaky.has(v.testId));
24
- }
19
+ // src/action/baseline.ts
20
+ import { createHash as createHash2 } from "crypto";
21
+ import { existsSync as existsSync2, mkdirSync as mkdirSync2, readFileSync as readFileSync2, writeFileSync as writeFileSync2 } from "fs";
22
+ import path2 from "path";
25
23
 
26
- // src/config.ts
27
- import { existsSync, readFileSync, statSync } from "fs";
24
+ // src/store/history-store.ts
25
+ import { createHash, randomBytes } from "crypto";
26
+ import {
27
+ closeSync,
28
+ existsSync,
29
+ fstatSync,
30
+ linkSync,
31
+ mkdirSync,
32
+ openSync,
33
+ readFileSync,
34
+ readSync,
35
+ rmSync,
36
+ statSync,
37
+ writeFileSync
38
+ } from "fs";
39
+ import { hostname } from "os";
28
40
  import path from "path";
29
- var CONFIG_FILE_NAME = "flakefinder.config.json";
30
- function stripJsonComments(text2) {
31
- let out = "";
32
- let i = 0;
33
- let inString = false;
34
- let quote = "";
35
- while (i < text2.length) {
36
- const c = text2[i];
37
- const next = text2[i + 1];
38
- if (inString) {
39
- if (c === "\\") {
40
- out += c + (next ?? "");
41
- i += 2;
42
- continue;
43
- }
44
- if (c === quote) inString = false;
45
- out += c;
46
- i++;
47
- continue;
48
- }
49
- if (c === '"' || c === "'") {
50
- inString = true;
51
- quote = c;
52
- out += c;
53
- i++;
54
- continue;
55
- }
56
- if (c === "/" && next === "/") {
57
- while (i < text2.length && text2[i] !== "\n") i++;
58
- continue;
59
- }
60
- if (c === "/" && next === "*") {
61
- i += 2;
62
- while (i < text2.length && !(text2[i] === "*" && text2[i + 1] === "/")) i++;
63
- i += 2;
64
- continue;
65
- }
66
- out += c;
67
- i++;
68
- }
69
- return stripTrailingCommas(out);
41
+
42
+ // src/util/atomic-rename.ts
43
+ import { renameSync } from "fs";
44
+ var RETRYABLE = /* @__PURE__ */ new Set(["EPERM", "EACCES", "EBUSY"]);
45
+ var RETRY_ATTEMPTS = 30;
46
+ function sleepSync(ms) {
47
+ Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms);
70
48
  }
71
- function stripTrailingCommas(text2) {
72
- let out = "";
73
- let inString = false;
74
- let quote = "";
75
- for (let i = 0; i < text2.length; i++) {
76
- const c = text2[i];
77
- if (inString) {
78
- out += c;
79
- if (c === "\\") {
80
- out += text2[i + 1] ?? "";
81
- i++;
82
- } else if (c === quote) {
83
- inString = false;
84
- }
85
- continue;
86
- }
87
- if (c === '"' || c === "'") {
88
- inString = true;
89
- quote = c;
90
- } else if (c === ",") {
91
- let j = i + 1;
92
- while (j < text2.length && /\s/.test(text2[j])) j++;
93
- if (text2[j] === "}" || text2[j] === "]") continue;
49
+ function renameOverSync(from, to, opts = {}) {
50
+ const platform = opts.platform ?? process.platform;
51
+ if (platform !== "win32") {
52
+ renameSync(from, to);
53
+ return;
54
+ }
55
+ const attempts = opts.attempts ?? RETRY_ATTEMPTS;
56
+ for (let attempt = 0; ; attempt++) {
57
+ try {
58
+ renameSync(from, to);
59
+ return;
60
+ } catch (err) {
61
+ const code = err.code ?? "";
62
+ if (attempt + 1 >= attempts || !RETRYABLE.has(code)) throw err;
63
+ sleepSync(Math.min(5 * (attempt + 1), 100));
94
64
  }
95
- out += c;
96
65
  }
97
- return out;
98
66
  }
99
- var ConfigValidationError = class extends Error {
67
+
68
+ // src/store/history-store.ts
69
+ function snapshotPath(storeDir) {
70
+ return path.join(storeDir, "verdicts-snapshot.json");
71
+ }
72
+ var STORE_FORMAT_VERSION = 1;
73
+ var StoreBusyError = class extends Error {
100
74
  };
101
- var KNOWN_KEYS = /* @__PURE__ */ new Set([
102
- "reports",
103
- "storeDir",
104
- "maxRuns",
105
- "minRuns",
106
- "liveRetries",
107
- "flakeScoreThreshold",
108
- "slowThresholdMs",
109
- "slowMultiplier",
110
- "quarantineFile",
111
- "runner",
112
- "failOnFlakes",
113
- "retryMode",
114
- "timeoutSeconds"
115
- ]);
116
- var VALID_RUNNERS = ["auto", "pytest", "jest", "mocha", "go", "generic"];
117
- function describe(v) {
118
- if (typeof v === "string") return `"${v}" (string)`;
119
- if (v === null) return "null";
120
- if (Array.isArray(v)) return "array";
121
- return `${String(v)} (${typeof v})`;
75
+ var LOCK_STALE_MS = 3e4;
76
+ var lockWaitState = new Int32Array(new SharedArrayBuffer(4));
77
+ function lockInTransition(code) {
78
+ return process.platform === "win32" && (code === "EPERM" || code === "EBUSY");
122
79
  }
123
- var TIMEOUT_MAX_SECONDS = 2147483;
124
- function checkInt(problems, key, v, min, max) {
125
- if (v === void 0) return;
126
- if (typeof v !== "number" || !Number.isInteger(v) || v < min || v > max) {
127
- problems.push(`${key}: expected integer ${min}\u2013${max}, got ${describe(v)}`);
128
- }
80
+ function uniqueSuffix() {
81
+ return `${process.pid}-${randomBytes(6).toString("hex")}`;
129
82
  }
130
- function validateConfig(config) {
131
- if (config === null || typeof config !== "object" || Array.isArray(config)) {
132
- throw new ConfigValidationError(
133
- `invalid flakefinder config: config must be a JSON object, got ${describe(config)}`
134
- );
135
- }
136
- const problems = [];
137
- for (const key of Object.keys(config)) {
138
- if (!KNOWN_KEYS.has(key)) {
139
- problems.push(`${key}: unknown key (valid keys: ${[...KNOWN_KEYS].sort().join(", ")})`);
83
+ function lockAgeMs(lockPath, content) {
84
+ if (content) {
85
+ try {
86
+ const holder = JSON.parse(content);
87
+ if (typeof holder.epoch === "number" && Number.isFinite(holder.epoch)) {
88
+ return Date.now() - holder.epoch;
89
+ }
90
+ } catch {
140
91
  }
141
92
  }
142
- const c = config;
143
- if (c.reports !== void 0) {
144
- const ok = Array.isArray(c.reports) && c.reports.every((x) => typeof x === "string" && x.trim() !== "");
145
- if (!ok)
146
- problems.push(
147
- `reports: expected array of non-empty glob strings, got ${describe(c.reports)}`
148
- );
149
- }
150
- if (c.storeDir !== void 0 && (typeof c.storeDir !== "string" || c.storeDir.trim() === "")) {
151
- problems.push(`storeDir: expected non-empty string, got ${describe(c.storeDir)}`);
152
- }
153
- checkInt(problems, "maxRuns", c.maxRuns, 1, 1e5);
154
- checkInt(problems, "minRuns", c.minRuns, 1, 1e3);
155
- checkInt(problems, "liveRetries", c.liveRetries, 0, 10);
156
- checkInt(problems, "flakeScoreThreshold", c.flakeScoreThreshold, 0, 100);
157
- if (c.slowThresholdMs !== void 0 && c.slowThresholdMs !== null && (typeof c.slowThresholdMs !== "number" || !Number.isFinite(c.slowThresholdMs) || c.slowThresholdMs <= 0)) {
158
- problems.push(
159
- `slowThresholdMs: expected positive number or null, got ${describe(c.slowThresholdMs)}`
160
- );
161
- }
162
- if (c.slowMultiplier !== void 0 && (typeof c.slowMultiplier !== "number" || !Number.isFinite(c.slowMultiplier) || c.slowMultiplier <= 0)) {
163
- problems.push(`slowMultiplier: expected positive number, got ${describe(c.slowMultiplier)}`);
164
- }
165
- if (c.quarantineFile !== void 0 && (typeof c.quarantineFile !== "string" || c.quarantineFile.trim() === "")) {
166
- problems.push(`quarantineFile: expected non-empty string, got ${describe(c.quarantineFile)}`);
93
+ try {
94
+ return Date.now() - statSync(lockPath).mtimeMs;
95
+ } catch {
96
+ return null;
167
97
  }
168
- if (c.runner !== void 0) {
169
- if (typeof c.runner !== "string" || !VALID_RUNNERS.includes(c.runner)) {
170
- const guess = VALID_RUNNERS.find(
171
- (r) => typeof c.runner === "string" && r.toLowerCase() === c.runner.toLowerCase()
172
- );
173
- problems.push(
174
- `runner: expected one of ${VALID_RUNNERS.join("|")}, got ${describe(c.runner)}` + (guess ? ` (did you mean "${guess}"?)` : "")
175
- );
176
- }
98
+ }
99
+ function ownerMayBeAlive(content) {
100
+ let owner;
101
+ try {
102
+ owner = JSON.parse(content);
103
+ } catch {
104
+ return false;
177
105
  }
178
- if (c.failOnFlakes !== void 0 && typeof c.failOnFlakes !== "boolean") {
179
- problems.push(`failOnFlakes: expected boolean, got ${describe(c.failOnFlakes)}`);
106
+ if (!isJsonObject(owner)) return false;
107
+ if (typeof owner.host === "string" && owner.host !== hostname()) return true;
108
+ if (typeof owner.pid !== "number" || !Number.isInteger(owner.pid) || owner.pid <= 0 || owner.pid > 2147483647) {
109
+ return false;
180
110
  }
181
- if (c.retryMode !== void 0) {
182
- const modes = ["auto", "failed", "full"];
183
- if (typeof c.retryMode !== "string" || !modes.includes(c.retryMode)) {
184
- problems.push(`retryMode: expected one of ${modes.join("|")}, got ${describe(c.retryMode)}`);
185
- }
111
+ try {
112
+ process.kill(owner.pid, 0);
113
+ return true;
114
+ } catch (err) {
115
+ return err.code !== "ESRCH";
186
116
  }
187
- if (c.timeoutSeconds !== null) {
188
- checkInt(problems, "timeoutSeconds", c.timeoutSeconds, 1, TIMEOUT_MAX_SECONDS);
117
+ }
118
+ function breakStaleLock(lockPath, observed) {
119
+ if (ownerMayBeAlive(observed)) return false;
120
+ const generation = createHash("sha256").update(observed).digest("hex").slice(0, 24);
121
+ const claim = `${lockPath}.recover-${generation}`;
122
+ let fd;
123
+ try {
124
+ fd = openSync(claim, "wx");
125
+ } catch {
126
+ return false;
189
127
  }
190
- if (problems.length > 0) {
191
- throw new ConfigValidationError(`invalid flakefinder config:
192
- - ${problems.join("\n - ")}`);
128
+ try {
129
+ const current = readFileSync(lockPath, "utf8");
130
+ const age = lockAgeMs(lockPath, current);
131
+ if (current !== observed || age === null || age <= LOCK_STALE_MS) return false;
132
+ rmSync(lockPath);
133
+ return true;
134
+ } catch {
135
+ return false;
136
+ } finally {
137
+ closeSync(fd);
138
+ rmSync(claim, { force: true });
193
139
  }
194
140
  }
195
- function resolveConfig(config = {}, overrides = {}) {
196
- validateConfig(config);
197
- validateConfig(overrides);
198
- return {
199
- reports: [],
200
- storeDir: ".flakefinder",
201
- maxRuns: 300,
202
- minRuns: 3,
203
- liveRetries: 2,
204
- flakeScoreThreshold: 30,
205
- slowThresholdMs: 1e4,
206
- slowMultiplier: 5,
207
- quarantineFile: "flakefinder.quarantine.json",
208
- runner: "auto",
209
- failOnFlakes: false,
210
- retryMode: "auto",
211
- timeoutSeconds: null,
212
- ...config,
213
- ...overrides
141
+ var warningListeners = /* @__PURE__ */ new Set();
142
+ function subscribeStoreWarnings(listener) {
143
+ warningListeners.add(listener);
144
+ return () => {
145
+ warningListeners.delete(listener);
214
146
  };
215
147
  }
216
- function anchorConfigPaths(config, configDir) {
217
- if (config === null || typeof config !== "object" || Array.isArray(config)) return config;
218
- const out = { ...config };
219
- for (const key of ["storeDir", "quarantineFile"]) {
220
- const v = out[key];
221
- if (typeof v === "string" && v.trim() !== "" && !path.isAbsolute(v)) {
222
- out[key] = path.resolve(configDir, v);
223
- }
148
+ function lastRuns(records, maxRuns) {
149
+ if (records.length <= maxRuns) return records;
150
+ const kept = /* @__PURE__ */ new Set();
151
+ for (let i = records.length - 1; i >= 0 && kept.size < maxRuns; i--) {
152
+ kept.add(records[i].runId);
224
153
  }
225
- return out;
154
+ if (kept.size === new Set(records.map((r) => r.runId)).size) return records;
155
+ return records.filter((r) => kept.has(r.runId));
226
156
  }
227
- function readConfigFile(file) {
228
- const abs = path.resolve(file);
229
- let raw;
230
- try {
231
- raw = readFileSync(abs, "utf8");
232
- } catch (err) {
233
- throw new Error(`cannot read config ${abs}: ${err.message}`);
234
- }
235
- let parsed;
236
- try {
237
- parsed = JSON.parse(stripJsonComments(raw.replace(/^\uFEFF/, "")));
238
- } catch (err) {
239
- throw new Error(`invalid config in ${abs}: ${err.message}`);
157
+ function isJsonObject(value) {
158
+ return typeof value === "object" && value !== null && !Array.isArray(value);
159
+ }
160
+ function isTestStatus(status) {
161
+ return status === "pass" || status === "fail" || status === "skip" || status === "error";
162
+ }
163
+ function isOptionalString(value) {
164
+ return value === void 0 || typeof value === "string";
165
+ }
166
+ function isTestResult(result) {
167
+ return isJsonObject(result) && typeof result.testId === "string" && typeof result.suite === "string" && typeof result.name === "string" && isTestStatus(result.status) && (result.durationMs === null || Number.isFinite(result.durationMs)) && isOptionalString(result.message) && isOptionalString(result.stack) && isOptionalString(result.file) && isOptionalString(result.playwrightProject) && isOptionalString(result.reportScope) && (result.reportedOutcome === void 0 || result.reportedOutcome === "expected" || result.reportedOutcome === "unexpected" || result.reportedOutcome === "flaky" || result.reportedOutcome === "skipped") && (result.attempts === void 0 || Array.isArray(result.attempts) && result.attempts.every(isTestStatus));
168
+ }
169
+ function hasValidRunData(record) {
170
+ return typeof record.runId === "string" && typeof record.timestamp === "string" && // Older or hand-authored history can omit execution metadata.
171
+ (record.attempt === void 0 || Number.isInteger(record.attempt)) && isOptionalString(record.commitSha) && isOptionalString(record.branch) && isOptionalString(record.ciRunId) && isOptionalString(record.reportFile) && Array.isArray(record.results) && record.results.every(isTestResult);
172
+ }
173
+ var HistoryStore = class _HistoryStore {
174
+ path;
175
+ warnings = [];
176
+ /** Schema version read from the file header; null for legacy header-less stores. */
177
+ formatVersion = null;
178
+ /**
179
+ * Set when `history.jsonl` exists but could not be read at all (EISDIR,
180
+ * EACCES, …): the store then behaves as empty, but callers that diagnose
181
+ * setup (doctor) must treat it as a hard failure, not as "0 runs".
182
+ * Holds `<errno>: <message>`; null when the file was read or is absent.
183
+ */
184
+ unreadable = null;
185
+ loaded = false;
186
+ records = [];
187
+ /** Content of the lock file this instance wrote; release only removes a lock that still matches. */
188
+ lockToken = null;
189
+ constructor(storeDir) {
190
+ this.path = path.join(storeDir, "history.jsonl");
240
191
  }
241
- if (parsed === null || typeof parsed !== "object" || Array.isArray(parsed)) {
242
- throw new Error(
243
- `invalid config in ${abs}: config must be a JSON object, got ${describe(parsed)}`
244
- );
192
+ /**
193
+ * Record a warning on this instance and tell any subscribers. Callers that
194
+ * never see the instance — `run` goes through runLive, which keeps its
195
+ * store private — subscribe instead of losing e.g. "prune skipped".
196
+ */
197
+ warn(message, first = false) {
198
+ if (first) this.warnings.unshift(message);
199
+ else this.warnings.push(message);
200
+ for (const listener of warningListeners) listener(message);
245
201
  }
246
- return anchorConfigPaths(parsed, path.dirname(abs));
247
- }
248
- function loadConfig(cwd) {
249
- let dir = path.resolve(cwd);
250
- for (let depth = 0; depth <= 3; depth++) {
251
- const candidate = path.join(dir, CONFIG_FILE_NAME);
252
- if (existsSync(candidate)) {
253
- return { config: readConfigFile(candidate), path: candidate };
254
- }
255
- const parent = path.dirname(dir);
256
- if (parent === dir) break;
257
- dir = parent;
202
+ ensureStoreDir() {
203
+ mkdirSync(path.dirname(this.path), { recursive: true });
258
204
  }
259
- return { config: {}, path: null };
260
- }
261
- function detectRunner(cwd) {
262
- const has = (f) => {
205
+ ensureLoaded() {
206
+ if (this.loaded) return;
207
+ this.loaded = true;
208
+ if (!existsSync(this.path)) return;
209
+ let raw;
263
210
  try {
264
- statSync(path.join(cwd, f));
265
- return true;
266
- } catch {
267
- return false;
211
+ raw = readFileSync(this.path, "utf8");
212
+ } catch (err) {
213
+ const e = err;
214
+ const code = e.code ?? "error";
215
+ this.unreadable = e.message.startsWith(code) ? e.message : `${code}: ${e.message}`;
216
+ this.warn(`history store unreadable (${code}): ${this.path}`);
217
+ return;
268
218
  }
269
- };
270
- if (has("package.json")) {
219
+ let start = 0;
220
+ let lineNo = 0;
221
+ while (start < raw.length) {
222
+ let end = raw.indexOf("\n", start);
223
+ if (end === -1) end = raw.length;
224
+ const line = raw.slice(start, end).trim();
225
+ lineNo++;
226
+ this.processLine(line, lineNo);
227
+ start = end + 1;
228
+ }
229
+ if (this.formatVersion !== null && this.formatVersion > STORE_FORMAT_VERSION) {
230
+ this.warn(
231
+ `store format v${this.formatVersion} is newer than this flakefinder (v${STORE_FORMAT_VERSION}) \u2014 some records may be unreadable`,
232
+ true
233
+ );
234
+ }
235
+ }
236
+ processLine(line, i) {
237
+ if (!line) return;
238
+ let parsed;
271
239
  try {
272
- const pkg = JSON.parse(readFileSync(path.join(cwd, "package.json"), "utf8"));
273
- const deps = { ...pkg.dependencies, ...pkg.devDependencies };
274
- const scripts = JSON.stringify(pkg.scripts ?? {});
275
- if (deps.jest || deps.vitest || /\b(jest|vitest)\b/.test(scripts)) return "jest";
276
- if (deps.mocha || /\bmocha\b/.test(scripts)) return "mocha";
240
+ parsed = JSON.parse(line);
277
241
  } catch {
242
+ if (this.warnings.length < 10) {
243
+ this.warn(`skipping corrupt line ${i} in ${this.path}`);
244
+ }
245
+ return;
278
246
  }
279
- }
280
- if (has("pyproject.toml") || has("pytest.ini") || has("setup.py") || has("setup.cfg"))
281
- return "pytest";
282
- if (has(".mocharc.yml") || has(".mocharc.json") || has(".mocharc.js") || has(".mocharc.cjs"))
283
- return "mocha";
284
- if (has("go.mod")) return "go";
285
- return "generic";
286
- }
287
-
288
- // src/doctor.ts
289
- import { spawnSync } from "child_process";
290
- import { existsSync as existsSync4, statSync as statSync4 } from "fs";
291
- import path5 from "path";
292
-
293
- // src/quarantine/manager.ts
294
- import { existsSync as existsSync2, linkSync, readFileSync as readFileSync2, rmSync, statSync as statSync2, writeFileSync } from "fs";
295
- import path2 from "path";
296
-
297
- // src/runner/adapters.ts
298
- function escapeRegExp(s) {
299
- return s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
300
- }
301
- function titleAlternation(names) {
302
- const alts = names.map((n) => escapeRegExp(n.trim()).replace(/ > /g, "(?: > | )"));
303
- return [...new Set(alts)].join("|");
304
- }
305
- function failedNamesOf(records) {
306
- const names = /* @__PURE__ */ new Set();
307
- for (const r of records) {
308
- for (const t of r.results) {
309
- if (t.status === "fail" || t.status === "error") names.add(t.name);
247
+ if (!isJsonObject(parsed)) {
248
+ if (this.warnings.length < 10) {
249
+ this.warn(`skipping record-shaped garbage at line ${i} in ${this.path}`);
250
+ }
251
+ return;
310
252
  }
311
- }
312
- return [...names];
313
- }
314
- function failedOnlyArgs(runner, failedNames, quarantinedNames = []) {
315
- if (failedNames.length === 0) return null;
316
- switch (runner) {
317
- case "jest":
318
- case "mocha": {
319
- const include = titleAlternation(failedNames);
320
- const exclude = titleAlternation(quarantinedNames);
321
- const pattern = exclude !== "" ? `^(?=(?:.* )?(?:${include})\\s*$)(?!(?:.* )?(?:${exclude})\\s*$)` : `^(?:.* )?(?:${include})\\s*$`;
322
- return runner === "jest" ? ["-t", pattern] : ["--grep", pattern];
253
+ if (parsed.runId === void 0 && parsed.results === void 0) {
254
+ if (typeof parsed.version === "number") {
255
+ if (i === 1) this.formatVersion = parsed.version;
256
+ else if (this.warnings.length < 10) {
257
+ this.warn(`unexpected schema marker at line ${i} \u2014 skipped`);
258
+ }
259
+ return;
260
+ }
261
+ if (this.warnings.length < 10) {
262
+ this.warn(`skipping record-shaped garbage at line ${i} in ${this.path}`);
263
+ }
264
+ return;
323
265
  }
324
- case "go": {
325
- const parents = new Set(failedNames.map((n) => n.includes("/") ? n.split("/")[0] : n));
326
- const pattern = `^(${[...parents].map(escapeRegExp).join("|")})$`;
327
- return ["-run", pattern];
266
+ if (!hasValidRunData(parsed)) {
267
+ if (this.warnings.length < 10) {
268
+ this.warn(`skipping invalid record at line ${i} in ${this.path}`);
269
+ }
270
+ return;
328
271
  }
329
- case "pytest":
330
- return ["--lf"];
331
- default:
332
- return null;
333
- }
334
- }
335
-
336
- // src/util/atomic-rename.ts
337
- import { renameSync } from "fs";
338
- var RETRYABLE = /* @__PURE__ */ new Set(["EPERM", "EACCES", "EBUSY"]);
339
- var RETRY_ATTEMPTS = 30;
340
- function sleepSync(ms) {
341
- Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms);
342
- }
343
- function renameOverSync(from, to, opts = {}) {
344
- const platform = opts.platform ?? process.platform;
345
- if (platform !== "win32") {
346
- renameSync(from, to);
347
- return;
272
+ parsed.attempt ??= 1;
273
+ this.records.push(parsed);
348
274
  }
349
- const attempts = opts.attempts ?? RETRY_ATTEMPTS;
350
- for (let attempt = 0; ; attempt++) {
275
+ /** Append one complete line even if a prior write ended before its newline. */
276
+ appendLine(run) {
277
+ const line = JSON.stringify(run);
278
+ const fd = openSync(this.path, "a+");
351
279
  try {
352
- renameSync(from, to);
353
- return;
354
- } catch (err) {
355
- const code = err.code ?? "";
356
- if (attempt + 1 >= attempts || !RETRYABLE.has(code)) throw err;
357
- sleepSync(Math.min(5 * (attempt + 1), 100));
280
+ const size = fstatSync(fd).size;
281
+ let prefix = "";
282
+ if (size === 0) {
283
+ prefix = `${JSON.stringify({ version: STORE_FORMAT_VERSION })}
284
+ `;
285
+ } else {
286
+ const tail = Buffer.alloc(1);
287
+ readSync(fd, tail, 0, 1, size - 1);
288
+ if (tail[0] !== 10) prefix = "\n";
289
+ }
290
+ writeFileSync(fd, `${prefix}${line}
291
+ `, "utf8");
292
+ if (size === 0) this.formatVersion = STORE_FORMAT_VERSION;
293
+ } finally {
294
+ closeSync(fd);
358
295
  }
359
296
  }
360
- }
361
-
362
- // src/quarantine/manager.ts
363
- var EMPTY = { version: 1, entries: [] };
364
- function applyOp(entries, op) {
365
- if (op.kind === "remove") return entries.filter((e) => e.testId !== op.testId);
366
- if (op.kind === "prune") {
367
- return entries.filter((e) => e.testId !== op.testId || e.quarantinedAt !== op.quarantinedAt);
368
- }
369
- const prior = entries.find((e) => e.testId === op.entry.testId);
370
- const entry = prior?.quarantinedAt ? { ...op.entry, quarantinedAt: prior.quarantinedAt } : op.entry;
371
- return [...entries.filter((e) => e.testId !== op.entry.testId), entry];
372
- }
373
- var LOCK_TIMEOUT_MS = 1e4;
374
- var LOCK_STALE_MS = 3e4;
375
- function sleepSync2(ms) {
376
- Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms);
377
- }
378
- function lockPid(content) {
379
- try {
380
- const parsed = JSON.parse(content);
381
- if (typeof parsed === "object" && parsed !== null && typeof parsed.pid === "number") {
382
- return parsed.pid;
383
- }
384
- } catch {
385
- }
386
- return Number.parseInt(content, 10);
387
- }
388
- function removeQuietly(target) {
389
- try {
390
- rmSync(target, { force: true });
391
- return true;
392
- } catch {
393
- return false;
394
- }
395
- }
396
- function removePartialLock(lockPath, token) {
397
- try {
398
- const content = readFileSync2(lockPath, "utf8");
399
- if (content !== "" && !token.startsWith(content)) return;
400
- } catch {
401
- return;
297
+ get lockPath() {
298
+ return `${this.path}.lock`;
402
299
  }
403
- removeQuietly(lockPath);
404
- }
405
- function tryCreateLock(lockPath) {
406
- const token = JSON.stringify({
407
- pid: process.pid,
408
- epoch: Date.now(),
409
- nonce: `${Date.now().toString(36)}${Math.random().toString(36).slice(2, 8)}`
410
- });
411
- const tmp = `${lockPath}.${process.pid}.${Date.now().toString(36)}.${Math.random().toString(36).slice(2, 8)}.tmp`;
412
- try {
413
- writeFileSync(tmp, token, "utf8");
414
- try {
415
- linkSync(tmp, lockPath);
416
- return token;
417
- } catch (err) {
418
- const code = err.code;
419
- if (code === "EEXIST") return null;
420
- try {
421
- writeFileSync(lockPath, token, { flag: "wx" });
422
- } catch (fallbackErr) {
423
- if (fallbackErr.code === "EEXIST") return null;
424
- removePartialLock(lockPath, token);
425
- throw fallbackErr;
300
+ /**
301
+ * Advisory lock around writes (append/prune). Two CI matrix shards writing
302
+ * multi-KB records can interleave in one append and corrupt a line — the
303
+ * lock serializes them. Busy-waits in ≤50 ms slices (Atomics.wait) up to 2 s
304
+ * before giving up with an actionable error; a lock older than 30 s is
305
+ * reclaimed only when its host/process information permits recovery.
306
+ *
307
+ * The lock file is created atomically WITH its content (write a private
308
+ * temp file, then link() it into place — link fails if the lock exists), so
309
+ * competitors never see a half-written lock. Empty/unparseable locks (older
310
+ * flakefinder versions, torn writes) are aged by mtime, and stale locks are
311
+ * reclaimed one waiter at a time (breakStaleLock).
312
+ */
313
+ acquireLock() {
314
+ const deadline = Date.now() + 2e3;
315
+ for (; ; ) {
316
+ if (this.tryCreateLock()) return;
317
+ if (Date.now() >= deadline) {
318
+ throw new StoreBusyError(
319
+ `history store is busy (held by another flakefinder process for >2s): ${this.lockPath}. Run ingest steps serially, or give each CI shard its own storeDir. If the writer stopped on another host or during lock recovery, verify all writers have stopped before removing the abandoned lock and its .recover-* file.`
320
+ );
426
321
  }
322
+ let content;
427
323
  try {
428
- if (readFileSync2(lockPath, "utf8") !== token) return null;
429
- } catch {
430
- return null;
324
+ content = readFileSync(this.lockPath, "utf8");
325
+ } catch (err) {
326
+ const code = err.code;
327
+ if (code === "ENOENT") continue;
328
+ if (!lockInTransition(code)) {
329
+ throw this.lockError(code, "exists but cannot be read as a lock file");
330
+ }
431
331
  }
432
- return token;
332
+ if (content !== void 0) {
333
+ const ageMs = lockAgeMs(this.lockPath, content);
334
+ if (ageMs === null) continue;
335
+ if (ageMs > LOCK_STALE_MS && breakStaleLock(this.lockPath, content)) continue;
336
+ }
337
+ Atomics.wait(lockWaitState, 0, 0, 50);
433
338
  }
434
- } finally {
435
- removeQuietly(tmp);
436
- }
437
- }
438
- function processAlive(pid) {
439
- try {
440
- process.kill(pid, 0);
441
- return true;
442
- } catch (err) {
443
- const code = err.code;
444
- return code !== "ESRCH" && code !== "EINVAL" && code !== "ERANGE" && code !== "ERR_INVALID_ARG_TYPE" && code !== "ERR_OUT_OF_RANGE";
445
- }
446
- }
447
- function contentIsStale(content, ageMs) {
448
- const pid = lockPid(content);
449
- if (Number.isInteger(pid) && pid > 0) {
450
- return pid === process.pid || !processAlive(pid);
451
339
  }
452
- return ageMs > LOCK_STALE_MS;
453
- }
454
- function lockState(lockPath) {
455
- let content;
456
- let mtimeMs;
457
- try {
458
- content = readFileSync2(lockPath, "utf8");
459
- mtimeMs = statSync2(lockPath).mtimeMs;
460
- } catch (err) {
461
- const code = err.code;
462
- if (code === "ENOENT") return { state: "missing" };
463
- if (code === "EPERM" || code === "EBUSY" || code === "EACCES") return { state: "live" };
464
- throw new Error(
465
- `quarantine lock ${lockPath} exists but cannot be read as a lock file (${code ?? "error"}) \u2014 check that the quarantine directory is writable and that the lock path is not a directory`
340
+ lockError(code, what) {
341
+ return new Error(
342
+ `history store lock ${this.lockPath} ${what} (${code ?? "error"}) \u2014 check that the store directory is writable and that the lock path is not a directory`
466
343
  );
467
344
  }
468
- return contentIsStale(content, Date.now() - mtimeMs) ? { state: "stale", content } : { state: "live" };
469
- }
470
- function tryTakeBreaker(breakPath) {
471
- for (let attempt = 0; attempt < 2; attempt++) {
472
- const token = tryCreateLock(breakPath);
473
- if (token !== null) return token;
345
+ /**
346
+ * One attempt to take the lock: true on success, false when another process
347
+ * holds it (EEXIST) or Windows reports it is in transition. Permanent errors
348
+ * such as a read-only directory (EACCES,
349
+ * EROFS), missing dir, … — throws: retrying cannot fix it, and treating it
350
+ * as "held" used to spin forever.
351
+ */
352
+ tryCreateLock() {
353
+ const token = JSON.stringify({
354
+ pid: process.pid,
355
+ host: hostname(),
356
+ epoch: Date.now(),
357
+ nonce: randomBytes(6).toString("hex")
358
+ });
359
+ const tmp = `${this.lockPath}.${uniqueSuffix()}.tmp`;
474
360
  try {
475
- const content = readFileSync2(breakPath, "utf8");
476
- const age = Date.now() - statSync2(breakPath).mtimeMs;
477
- if (contentIsStale(content, age)) {
478
- if (!removeQuietly(breakPath)) return null;
479
- continue;
480
- }
481
- } catch {
361
+ writeFileSync(tmp, token, "utf8");
362
+ } catch (err) {
363
+ throw this.lockError(err.code, "cannot be created");
482
364
  }
483
- return null;
484
- }
485
- return null;
486
- }
487
- function breakStaleLock(lockPath, observed) {
488
- const breakPath = `${lockPath}.break`;
489
- const breakerToken = tryTakeBreaker(breakPath);
490
- if (breakerToken === null) return false;
491
- try {
492
- let content;
493
- let mtimeMs;
494
365
  try {
495
- content = readFileSync2(lockPath, "utf8");
496
- mtimeMs = statSync2(lockPath).mtimeMs;
497
- } catch {
498
- return false;
366
+ linkSync(tmp, this.lockPath);
367
+ this.lockToken = token;
368
+ return true;
369
+ } catch (err) {
370
+ const code = err.code;
371
+ if (code === "EEXIST") return false;
372
+ try {
373
+ writeFileSync(this.lockPath, token, { flag: "wx" });
374
+ this.lockToken = token;
375
+ return true;
376
+ } catch (err2) {
377
+ const code2 = err2.code;
378
+ if (code2 === "EEXIST" || lockInTransition(code2)) return false;
379
+ throw this.lockError(code2, "cannot be created");
380
+ }
381
+ } finally {
382
+ rmSync(tmp, { force: true });
499
383
  }
500
- if (content !== observed || !contentIsStale(content, Date.now() - mtimeMs)) return false;
501
- return removeQuietly(lockPath);
502
- } finally {
384
+ }
385
+ releaseLock() {
386
+ const token = this.lockToken;
387
+ this.lockToken = null;
503
388
  try {
504
- if (readFileSync2(breakPath, "utf8") === breakerToken) removeQuietly(breakPath);
389
+ if (readFileSync(this.lockPath, "utf8") === token) rmSync(this.lockPath, { force: true });
505
390
  } catch {
506
391
  }
507
392
  }
508
- }
509
- function withFileLock(target, fn) {
510
- const lockPath = `${target}.lock`;
511
- const deadline = Date.now() + LOCK_TIMEOUT_MS;
512
- let token;
513
- for (; ; ) {
514
- const acquired = tryCreateLock(lockPath);
515
- if (acquired !== null) {
516
- token = acquired;
517
- break;
518
- }
519
- if (Date.now() > deadline) {
393
+ loadAll() {
394
+ this.ensureLoaded();
395
+ return [...this.records];
396
+ }
397
+ runs() {
398
+ this.ensureLoaded();
399
+ return [...this.records];
400
+ }
401
+ /**
402
+ * Write paths must not surface raw EISDIR/EACCES: a directory (or other
403
+ * non-file) at the store path is a setup error that should name the file.
404
+ */
405
+ assertWritableFile() {
406
+ if (existsSync(this.path) && !statSync(this.path).isFile()) {
520
407
  throw new Error(
521
- `quarantine file is locked by another flakefinder process (${lockPath}) \u2014 delete the lock if no other flakefinder is running`
408
+ `history store ${this.path} exists but is not a regular file \u2014 delete or rename it (flakefinder recreates it on the next write)`
522
409
  );
523
410
  }
524
- const state = lockState(lockPath);
525
- if (state.state === "missing") continue;
526
- if (state.state === "stale") {
527
- if (!breakStaleLock(lockPath, state.content)) {
528
- sleepSync2(5 + Math.floor(Math.random() * 15));
529
- }
530
- continue;
531
- }
532
- sleepSync2(10 + Math.floor(Math.random() * 20));
533
411
  }
534
- try {
535
- return fn();
536
- } finally {
412
+ /**
413
+ * Appends without reading the store: when this instance has not loaded the
414
+ * file yet, the record simply becomes part of the next (lazy) read.
415
+ */
416
+ append(run) {
417
+ this.ensureStoreDir();
418
+ this.assertWritableFile();
419
+ this.acquireLock();
537
420
  try {
538
- const current = readFileSync2(lockPath, "utf8");
539
- const ours = current === token;
540
- if (ours) {
541
- rmSync(lockPath, { force: true });
421
+ try {
422
+ this.appendLine(run);
423
+ } catch (err) {
424
+ const e = err;
425
+ throw new Error(
426
+ `cannot write history store ${this.path} (${e.code ?? "error"}) \u2014 check it is a writable regular file`
427
+ );
542
428
  }
543
- } catch {
429
+ if (this.loaded) this.records.push(run);
430
+ } finally {
431
+ this.releaseLock();
544
432
  }
545
433
  }
546
- }
547
- var QuarantineManager = class {
548
- filePath;
549
- file;
550
- pending = [];
551
- constructor(filePath) {
552
- this.filePath = filePath;
553
- this.file = this.load();
554
- }
555
- load() {
556
- if (!existsSync2(this.filePath)) return { ...EMPTY, entries: [] };
557
- try {
558
- const parsed = JSON.parse(readFileSync2(this.filePath, "utf8"));
559
- if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) {
560
- throw new Error("expected a JSON object");
561
- }
562
- const obj = parsed;
563
- if (!Array.isArray(obj.entries)) throw new Error('missing "entries" array');
564
- obj.entries.forEach((e, i) => {
565
- if (typeof e !== "object" || e === null || Array.isArray(e)) {
566
- throw new Error(`entry #${i + 1} is not an object`);
567
- }
568
- for (const field of ["testId", "suite", "name"]) {
569
- const value = e[field];
570
- if (typeof value !== "string" || value === "") {
571
- throw new Error(`entry #${i + 1} has no string "${field}"`);
572
- }
573
- }
574
- });
575
- return { ...obj, version: 1, entries: obj.entries };
576
- } catch (err) {
577
- throw new Error(`invalid quarantine file ${this.filePath}: ${err.message}`);
578
- }
579
- }
580
- apply(op) {
581
- this.pending.push(op);
582
- this.file.entries = applyOp(this.file.entries, op);
583
- }
584
- list() {
585
- return [...this.file.entries];
586
- }
587
- /** Add or replace an entry (same testId); a re-add keeps the original quarantinedAt. */
588
- add(entry) {
589
- this.apply({ kind: "add", entry });
590
- }
591
- remove(testId) {
592
- const existed = this.file.entries.some((e) => e.testId === testId);
593
- if (existed) this.apply({ kind: "remove", testId });
594
- return existed;
595
- }
596
434
  /**
597
- * Drop entries that no longer deserve quarantine. Deliberately
598
- * conservative: quarantined tests are excluded from runs, so "not seen
599
- * lately" is NOT evidence of health (that would silently un-quarantine
600
- * everything). An entry leaves quarantine only on positive evidence —
601
- * the test ran (quarantine disabled or full-suite run) since it was
602
- * quarantined and passed stably — or when the entry is older than 90 days and the test is gone from
603
- * history. Returns the removed entries.
435
+ * Keep only the last `maxRuns` RUNS (distinct runIds — one `run` with
436
+ * retries writes one record per attempt, all sharing a runId, and they are
437
+ * kept or dropped together); rewrite the file atomically.
438
+ * Re-reads the file FRESH inside the lock: a stale in-memory snapshot
439
+ * would silently delete records another process appended between our load
440
+ * and this prune (verified 10/10 with two concurrent ingests before the
441
+ * fix). In-memory records are resynced to the fresh state — including an
442
+ * empty one: the stale view is only kept when the fresh read FAILED, and
443
+ * then nothing is rewritten.
604
444
  */
605
- prune(verdicts, runs = [], maxAgeDays = 90) {
606
- if (verdicts.length === 0) return [];
607
- const byId = new Map(verdicts.map((v) => [v.testId, v]));
608
- const latestPass = /* @__PURE__ */ new Map();
609
- for (const run of runs) {
610
- const time = Date.parse(run.timestamp);
611
- for (const test of run.results) {
612
- if (test.status === "pass" && time > (latestPass.get(test.testId) ?? -Infinity)) {
613
- latestPass.set(test.testId, time);
445
+ prune(maxRuns) {
446
+ if (this.unreadable) return;
447
+ if (!existsSync(this.path)) return;
448
+ this.ensureStoreDir();
449
+ try {
450
+ this.acquireLock();
451
+ } catch (err) {
452
+ if (!(err instanceof StoreBusyError)) throw err;
453
+ this.warn(`history store busy \u2014 prune skipped this time: ${this.path}`);
454
+ return;
455
+ }
456
+ try {
457
+ const fresh = new _HistoryStore(path.dirname(this.path));
458
+ const source = fresh.runs();
459
+ if (fresh.unreadable !== null) {
460
+ if (this.loaded) {
461
+ this.warn(`history store unreadable during prune \u2014 not pruned: ${this.path}`);
462
+ } else {
463
+ this.adopt(fresh);
614
464
  }
465
+ return;
615
466
  }
616
- }
617
- const removed = [];
618
- for (const entry of this.file.entries) {
619
- const v = byId.get(entry.testId);
620
- const quarantinedMs = Date.parse(entry.quarantinedAt);
621
- const passedAt = v?.lastStatus === "pass" ? Date.parse(v.lastSeen) : latestPass.get(entry.testId);
622
- const healthy = v?.classification === "passing" && v.runsObserved >= 10 && passedAt !== void 0 && passedAt >= quarantinedMs;
623
- const agedOut = v?.classification === "gone" && !Number.isNaN(quarantinedMs) && Date.now() - quarantinedMs > maxAgeDays * 864e5;
624
- if (healthy || agedOut) removed.push(entry);
625
- }
626
- for (const { testId, quarantinedAt } of removed)
627
- this.apply({ kind: "prune", testId, quarantinedAt });
628
- return removed;
629
- }
630
- /**
631
- * Persist this manager's changes. Under the lockfile: re-read the file
632
- * (another process may have saved since our constructor ran), replay our
633
- * pending operations onto it, then write atomically — a temp file in the
634
- * same directory renamed over the target, so neither a crash nor a
635
- * concurrent reader ever sees a torn file.
636
- */
637
- save() {
638
- withFileLock(this.filePath, () => {
639
- const fresh = this.load();
640
- for (const op of this.pending) fresh.entries = applyOp(fresh.entries, op);
641
- const tmp = `${this.filePath}.${process.pid}.${Date.now().toString(36)}.tmp`;
467
+ if (fresh.formatVersion !== null && fresh.formatVersion > STORE_FORMAT_VERSION) {
468
+ this.adopt(fresh);
469
+ this.warn(
470
+ `history prune skipped for newer store format v${fresh.formatVersion}: ${this.path}`
471
+ );
472
+ return;
473
+ }
474
+ const keep = lastRuns(source, maxRuns);
475
+ if (keep.length === source.length) {
476
+ this.adopt(fresh);
477
+ return;
478
+ }
479
+ const version = STORE_FORMAT_VERSION;
480
+ const tmp = `${this.path}.tmp`;
481
+ const fd = openSync(tmp, "w");
642
482
  try {
643
- writeFileSync(tmp, `${JSON.stringify(fresh, null, 2)}
483
+ writeFileSync(fd, `${JSON.stringify({ version })}
644
484
  `, "utf8");
645
- renameOverSync(tmp, this.filePath);
646
- } catch (err) {
647
- rmSync(tmp, { force: true });
648
- throw err;
485
+ for (const r of keep) writeFileSync(fd, `${JSON.stringify(r)}
486
+ `, "utf8");
487
+ } finally {
488
+ closeSync(fd);
649
489
  }
650
- this.file = fresh;
651
- this.pending = [];
652
- });
490
+ renameOverSync(tmp, this.path);
491
+ this.adopt(fresh);
492
+ this.records = keep;
493
+ this.formatVersion = version;
494
+ } finally {
495
+ this.releaseLock();
496
+ }
653
497
  }
654
- };
655
- var ROOT_MARKERS = ["pytest.ini", "pyproject.toml", "tox.ini", "setup.cfg", "setup.py", ".git"];
656
- function existsUpward(cwd, rel) {
657
- let dir = path2.resolve(cwd);
658
- for (; ; ) {
659
- if (existsSync2(path2.join(dir, rel))) return true;
660
- const parent = path2.dirname(dir);
661
- if (parent === dir || ROOT_MARKERS.some((m) => existsSync2(path2.join(dir, m)))) return false;
662
- dir = parent;
498
+ /** Resync this instance's view to a fresh read of the same store. */
499
+ adopt(fresh) {
500
+ if (!this.loaded) this.warnings.push(...fresh.warnings);
501
+ this.loaded = true;
502
+ this.records = fresh.runs();
503
+ this.formatVersion = fresh.formatVersion;
504
+ this.unreadable = fresh.unreadable;
663
505
  }
506
+ };
507
+
508
+ // src/action/baseline.ts
509
+ function baselinePath(storeDir) {
510
+ return path2.join(storeDir, "action-baseline.json");
664
511
  }
665
- function pytestNodeId(suite, name, cwd) {
666
- if (/[\\/]|::|\.py$/.test(suite)) return `${suite.replace(/\\/g, "/")}::${name}`;
667
- const parts = suite.split(".").filter((p) => p !== "");
668
- if (parts.length === 0) return name;
669
- let moduleEnd = 0;
670
- if (cwd !== void 0) {
671
- for (let i = parts.length; i >= 1; i--) {
672
- if (existsUpward(cwd, `${parts.slice(0, i).join("/")}.py`)) {
673
- moduleEnd = i;
674
- break;
675
- }
676
- }
677
- }
678
- if (moduleEnd === 0) {
679
- moduleEnd = 1;
680
- for (let i = parts.length - 1; i >= 1; i--) {
681
- if (!/^[A-Z]/.test(parts[i])) {
682
- moduleEnd = i + 1;
683
- break;
684
- }
685
- }
512
+ function readJson(file) {
513
+ if (!existsSync2(file)) return null;
514
+ try {
515
+ return { ok: true, value: JSON.parse(readFileSync2(file, "utf8")) };
516
+ } catch {
517
+ return { ok: false };
686
518
  }
687
- const file = `${parts.slice(0, moduleEnd).join("/")}.py`;
688
- return [file, ...parts.slice(moduleEnd), name].join("::");
689
519
  }
690
- function exclusionArgs(runner, entries, cwd) {
691
- if (entries.length === 0) return [];
692
- switch (runner) {
693
- case "pytest": {
694
- const args = [];
695
- for (const e of entries) args.push("--deselect", pytestNodeId(e.suite, e.name, cwd));
696
- return args;
520
+ function usableVerdicts(value) {
521
+ return Array.isArray(value) && value.every(
522
+ (v) => v !== null && typeof v === "object" && typeof v.testId === "string" && typeof v.classification === "string" && Number.isFinite(v.flakeScore)
523
+ );
524
+ }
525
+ function resolveBaseline(storeDir, runId, file = baselinePath(storeDir)) {
526
+ const warnings = [];
527
+ let previous = null;
528
+ let source = "none";
529
+ const recorded = readJson(file);
530
+ const rec = recorded?.ok ? recorded.value : null;
531
+ if (recorded && (!rec || typeof rec !== "object" || typeof rec.runId !== "string")) {
532
+ warnings.push("recorded baseline unreadable; treating this as a first run");
533
+ } else if (runId !== "" && rec !== null && typeof rec === "object" && rec.runId === runId) {
534
+ if (rec.previous === null || usableVerdicts(rec.previous)) {
535
+ previous = rec.previous;
536
+ source = "earlier-attempt";
537
+ } else {
538
+ warnings.push("recorded baseline unreadable; treating this as a first run");
697
539
  }
698
- case "jest":
699
- case "mocha": {
700
- const flag = runner === "jest" ? "-t" : "--grep";
701
- return [flag, `^(?!(?:.* )?(?:${titleAlternation(entries.map((e) => e.name))})\\s*$)`];
540
+ } else {
541
+ const snap = readJson(snapshotPath(storeDir));
542
+ if (snap?.ok && usableVerdicts(snap.value)) {
543
+ previous = snap.value;
544
+ source = "snapshot";
545
+ } else if (snap !== null) {
546
+ warnings.push("previous verdict snapshot unreadable \u2014 treating this as a first run");
702
547
  }
703
- // go / generic: no per-test exclusion — callers must warn
704
- default:
705
- return [];
706
548
  }
549
+ return { previous, source, warnings };
707
550
  }
708
- var PYTEST_EXACT_PLUGIN_MODULE = "flakefinder_exact_deselect";
709
- var PYTEST_EXACT_ENV = "FLAKEFINDER_EXACT_DESELECT";
710
- var PYTEST_EXACT_PLUGIN_SOURCE = `# Generated by flakefinder: exact quarantine deselection (temporary file).
711
- import json
712
- import os
713
-
714
- import pytest
715
-
716
-
717
- @pytest.hookimpl(tryfirst=True)
718
- def pytest_collection_modifyitems(config, items):
719
- try:
720
- ours = json.loads(os.environ.get("${PYTEST_EXACT_ENV}", "[]"))
721
- except ValueError:
722
- return
723
- if not isinstance(ours, list) or not ours:
724
- return
725
- remaining = list(config.getoption("deselect") or [])
726
- for node_id in ours:
727
- if node_id in remaining:
728
- remaining.remove(node_id)
729
- config.option.deselect = remaining
730
- exact = set(ours)
731
- keep, drop = [], []
732
- for item in items:
733
- nid = item.nodeid
734
- base = nid.split("[", 1)[0]
735
- (drop if nid in exact or base in exact else keep).append(item)
736
- if drop:
737
- config.hook.pytest_deselected(items=drop)
738
- items[:] = keep
739
- `;
740
- function pytestExactDeselectEnv(nodeIds, pluginDir, env = process.env) {
741
- const plugins = (env.PYTEST_PLUGINS ?? "").split(",").map((p) => p.trim()).filter((p) => p !== "" && p !== PYTEST_EXACT_PLUGIN_MODULE);
742
- const pythonPath = env.PYTHONPATH ? `${pluginDir}${path2.delimiter}${env.PYTHONPATH}` : pluginDir;
743
- return {
744
- ...env,
745
- PYTEST_PLUGINS: [...plugins, PYTEST_EXACT_PLUGIN_MODULE].join(","),
746
- PYTHONPATH: pythonPath,
747
- [PYTEST_EXACT_ENV]: JSON.stringify(nodeIds)
748
- };
551
+ function recordBaseline(storeDir, runId, previous, file = baselinePath(storeDir)) {
552
+ if (runId === "") return;
553
+ mkdirSync2(path2.dirname(file), { recursive: true });
554
+ const record = { runId, previous };
555
+ writeFileSync2(file, JSON.stringify(record), "utf8");
749
556
  }
750
- function deselectedNodeIds(args) {
751
- const ids = [];
752
- for (let i = 0; i < args.length - 1; i++) if (args[i] === "--deselect") ids.push(args[i + 1]);
753
- return ids;
557
+
558
+ // src/action/diff.ts
559
+ var FLAKY = /* @__PURE__ */ new Set(["flaky-confirmed", "flaky-retry", "flaky-suspected"]);
560
+ function computeNewFlakes(current, previous) {
561
+ const prevFlaky = new Set(
562
+ (previous ?? []).filter((v) => FLAKY.has(v.classification)).map((v) => v.testId)
563
+ );
564
+ return current.filter((v) => FLAKY.has(v.classification) && !prevFlaky.has(v.testId));
754
565
  }
755
566
 
756
- // src/store/history-store.ts
757
- import { createHash, randomBytes } from "crypto";
758
- import {
759
- closeSync,
760
- existsSync as existsSync3,
761
- fstatSync,
762
- linkSync as linkSync2,
763
- mkdirSync,
764
- openSync,
765
- readFileSync as readFileSync3,
766
- readSync,
767
- rmSync as rmSync2,
768
- statSync as statSync3,
769
- writeFileSync as writeFileSync2
770
- } from "fs";
771
- import { hostname } from "os";
567
+ // src/config.ts
568
+ import { existsSync as existsSync3, readFileSync as readFileSync3, statSync as statSync2 } from "fs";
772
569
  import path3 from "path";
773
- function snapshotPath(storeDir) {
774
- return path3.join(storeDir, "verdicts-snapshot.json");
775
- }
776
- var STORE_FORMAT_VERSION = 1;
777
- var StoreBusyError = class extends Error {
778
- };
779
- var LOCK_STALE_MS2 = 3e4;
780
- function uniqueSuffix() {
781
- return `${process.pid}-${randomBytes(6).toString("hex")}`;
570
+ var CONFIG_FILE_NAME = "flakefinder.config.json";
571
+ function stripJsonComments(text2) {
572
+ let out = "";
573
+ let i = 0;
574
+ let inString = false;
575
+ let quote = "";
576
+ while (i < text2.length) {
577
+ const c = text2[i];
578
+ const next = text2[i + 1];
579
+ if (inString) {
580
+ if (c === "\\") {
581
+ out += c + (next ?? "");
582
+ i += 2;
583
+ continue;
584
+ }
585
+ if (c === quote) inString = false;
586
+ out += c;
587
+ i++;
588
+ continue;
589
+ }
590
+ if (c === '"' || c === "'") {
591
+ inString = true;
592
+ quote = c;
593
+ out += c;
594
+ i++;
595
+ continue;
596
+ }
597
+ if (c === "/" && next === "/") {
598
+ while (i < text2.length && text2[i] !== "\n") i++;
599
+ continue;
600
+ }
601
+ if (c === "/" && next === "*") {
602
+ i += 2;
603
+ while (i < text2.length && !(text2[i] === "*" && text2[i + 1] === "/")) i++;
604
+ i += 2;
605
+ continue;
606
+ }
607
+ out += c;
608
+ i++;
609
+ }
610
+ return stripTrailingCommas(out);
782
611
  }
783
- function lockAgeMs(lockPath, content) {
784
- if (content) {
785
- try {
786
- const holder = JSON.parse(content);
787
- if (typeof holder.epoch === "number" && Number.isFinite(holder.epoch)) {
788
- return Date.now() - holder.epoch;
612
+ function stripTrailingCommas(text2) {
613
+ let out = "";
614
+ let inString = false;
615
+ let quote = "";
616
+ for (let i = 0; i < text2.length; i++) {
617
+ const c = text2[i];
618
+ if (inString) {
619
+ out += c;
620
+ if (c === "\\") {
621
+ out += text2[i + 1] ?? "";
622
+ i++;
623
+ } else if (c === quote) {
624
+ inString = false;
789
625
  }
790
- } catch {
626
+ continue;
627
+ }
628
+ if (c === '"' || c === "'") {
629
+ inString = true;
630
+ quote = c;
631
+ } else if (c === ",") {
632
+ let j = i + 1;
633
+ while (j < text2.length && /\s/.test(text2[j])) j++;
634
+ if (text2[j] === "}" || text2[j] === "]") continue;
791
635
  }
636
+ out += c;
792
637
  }
793
- try {
794
- return Date.now() - statSync3(lockPath).mtimeMs;
795
- } catch {
796
- return null;
638
+ return out;
639
+ }
640
+ var ConfigValidationError = class extends Error {
641
+ };
642
+ var KNOWN_KEYS = /* @__PURE__ */ new Set([
643
+ "reports",
644
+ "reportScopes",
645
+ "storeDir",
646
+ "maxRuns",
647
+ "minRuns",
648
+ "liveRetries",
649
+ "flakeScoreThreshold",
650
+ "slowThresholdMs",
651
+ "slowMultiplier",
652
+ "quarantineFile",
653
+ "runner",
654
+ "failOnFlakes",
655
+ "retryMode",
656
+ "timeoutSeconds"
657
+ ]);
658
+ var VALID_RUNNERS = ["auto", "pytest", "jest", "mocha", "go", "generic"];
659
+ function describe(v) {
660
+ if (typeof v === "string") return `"${v}" (string)`;
661
+ if (v === null) return "null";
662
+ if (Array.isArray(v)) return "array";
663
+ return `${String(v)} (${typeof v})`;
664
+ }
665
+ var TIMEOUT_MAX_SECONDS = 2147483;
666
+ function checkInt(problems, key, v, min, max) {
667
+ if (v === void 0) return;
668
+ if (typeof v !== "number" || !Number.isInteger(v) || v < min || v > max) {
669
+ problems.push(`${key}: expected integer ${min}\u2013${max}, got ${describe(v)}`);
797
670
  }
798
671
  }
799
- function ownerMayBeAlive(content) {
800
- let owner;
801
- try {
802
- owner = JSON.parse(content);
803
- } catch {
804
- return false;
672
+ function validateConfig(config) {
673
+ if (config === null || typeof config !== "object" || Array.isArray(config)) {
674
+ throw new ConfigValidationError(
675
+ `invalid flakefinder config: config must be a JSON object, got ${describe(config)}`
676
+ );
805
677
  }
806
- if (!isJsonObject(owner)) return false;
807
- if (typeof owner.host === "string" && owner.host !== hostname()) return true;
808
- if (typeof owner.pid !== "number" || !Number.isInteger(owner.pid) || owner.pid <= 0 || owner.pid > 2147483647) {
809
- return false;
678
+ const problems = [];
679
+ for (const key of Object.keys(config)) {
680
+ if (!KNOWN_KEYS.has(key)) {
681
+ problems.push(`${key}: unknown key (valid keys: ${[...KNOWN_KEYS].sort().join(", ")})`);
682
+ }
810
683
  }
811
- try {
812
- process.kill(owner.pid, 0);
813
- return true;
814
- } catch (err) {
815
- return err.code !== "ESRCH";
684
+ const c = config;
685
+ if (c.reports !== void 0) {
686
+ const ok = Array.isArray(c.reports) && c.reports.every((x) => typeof x === "string" && x.trim() !== "");
687
+ if (!ok)
688
+ problems.push(
689
+ `reports: expected array of non-empty glob strings, got ${describe(c.reports)}`
690
+ );
816
691
  }
817
- }
818
- function breakStaleLock2(lockPath, observed) {
819
- if (ownerMayBeAlive(observed)) return false;
820
- const generation = createHash("sha256").update(observed).digest("hex").slice(0, 24);
821
- const claim = `${lockPath}.recover-${generation}`;
822
- let fd;
823
- try {
824
- fd = openSync(claim, "wx");
825
- } catch {
826
- return false;
692
+ if (c.reportScopes !== void 0 && (c.reportScopes === null || typeof c.reportScopes !== "object" || Array.isArray(c.reportScopes) || !Object.entries(c.reportScopes).every(
693
+ ([glob, scope]) => glob.trim() !== "" && typeof scope === "string" && /^[\w.-]+$/.test(scope)
694
+ ))) {
695
+ problems.push(
696
+ "reportScopes: expected an object mapping globs to stable names (letters, numbers, _, -, .)"
697
+ );
827
698
  }
828
- try {
829
- const current = readFileSync3(lockPath, "utf8");
830
- const age = lockAgeMs(lockPath, current);
831
- if (current !== observed || age === null || age <= LOCK_STALE_MS2) return false;
832
- rmSync2(lockPath);
833
- return true;
834
- } catch {
835
- return false;
836
- } finally {
837
- closeSync(fd);
838
- rmSync2(claim, { force: true });
699
+ if (c.storeDir !== void 0 && (typeof c.storeDir !== "string" || c.storeDir.trim() === "")) {
700
+ problems.push(`storeDir: expected non-empty string, got ${describe(c.storeDir)}`);
701
+ }
702
+ checkInt(problems, "maxRuns", c.maxRuns, 1, 1e5);
703
+ checkInt(problems, "minRuns", c.minRuns, 1, 1e3);
704
+ checkInt(problems, "liveRetries", c.liveRetries, 0, 10);
705
+ checkInt(problems, "flakeScoreThreshold", c.flakeScoreThreshold, 0, 100);
706
+ if (c.slowThresholdMs !== void 0 && c.slowThresholdMs !== null && (typeof c.slowThresholdMs !== "number" || !Number.isFinite(c.slowThresholdMs) || c.slowThresholdMs <= 0)) {
707
+ problems.push(
708
+ `slowThresholdMs: expected positive number or null, got ${describe(c.slowThresholdMs)}`
709
+ );
710
+ }
711
+ if (c.slowMultiplier !== void 0 && (typeof c.slowMultiplier !== "number" || !Number.isFinite(c.slowMultiplier) || c.slowMultiplier <= 0)) {
712
+ problems.push(`slowMultiplier: expected positive number, got ${describe(c.slowMultiplier)}`);
713
+ }
714
+ if (c.quarantineFile !== void 0 && (typeof c.quarantineFile !== "string" || c.quarantineFile.trim() === "")) {
715
+ problems.push(`quarantineFile: expected non-empty string, got ${describe(c.quarantineFile)}`);
716
+ }
717
+ if (c.runner !== void 0) {
718
+ if (typeof c.runner !== "string" || !VALID_RUNNERS.includes(c.runner)) {
719
+ const guess = VALID_RUNNERS.find(
720
+ (r) => typeof c.runner === "string" && r.toLowerCase() === c.runner.toLowerCase()
721
+ );
722
+ problems.push(
723
+ `runner: expected one of ${VALID_RUNNERS.join("|")}, got ${describe(c.runner)}` + (guess ? ` (did you mean "${guess}"?)` : "")
724
+ );
725
+ }
726
+ }
727
+ if (c.failOnFlakes !== void 0 && typeof c.failOnFlakes !== "boolean") {
728
+ problems.push(`failOnFlakes: expected boolean, got ${describe(c.failOnFlakes)}`);
729
+ }
730
+ if (c.retryMode !== void 0) {
731
+ const modes = ["auto", "failed", "full"];
732
+ if (typeof c.retryMode !== "string" || !modes.includes(c.retryMode)) {
733
+ problems.push(`retryMode: expected one of ${modes.join("|")}, got ${describe(c.retryMode)}`);
734
+ }
735
+ }
736
+ if (c.timeoutSeconds !== null) {
737
+ checkInt(problems, "timeoutSeconds", c.timeoutSeconds, 1, TIMEOUT_MAX_SECONDS);
738
+ }
739
+ if (problems.length > 0) {
740
+ throw new ConfigValidationError(`invalid flakefinder config:
741
+ - ${problems.join("\n - ")}`);
839
742
  }
840
743
  }
841
- var warningListeners = /* @__PURE__ */ new Set();
842
- function subscribeStoreWarnings(listener) {
843
- warningListeners.add(listener);
844
- return () => {
845
- warningListeners.delete(listener);
744
+ function resolveConfig(config = {}, overrides = {}) {
745
+ validateConfig(config);
746
+ validateConfig(overrides);
747
+ return {
748
+ reports: [],
749
+ storeDir: ".flakefinder",
750
+ maxRuns: 300,
751
+ minRuns: 3,
752
+ liveRetries: 2,
753
+ flakeScoreThreshold: 30,
754
+ slowThresholdMs: 1e4,
755
+ slowMultiplier: 5,
756
+ quarantineFile: "flakefinder.quarantine.json",
757
+ runner: "auto",
758
+ failOnFlakes: false,
759
+ retryMode: "auto",
760
+ timeoutSeconds: null,
761
+ ...config,
762
+ ...overrides
846
763
  };
847
764
  }
848
- function lastRuns(records, maxRuns) {
849
- if (records.length <= maxRuns) return records;
850
- const kept = /* @__PURE__ */ new Set();
851
- for (let i = records.length - 1; i >= 0 && kept.size < maxRuns; i--) {
852
- kept.add(records[i].runId);
765
+ function anchorConfigPaths(config, configDir) {
766
+ if (config === null || typeof config !== "object" || Array.isArray(config)) return config;
767
+ const out = { ...config };
768
+ for (const key of ["storeDir", "quarantineFile"]) {
769
+ const v = out[key];
770
+ if (typeof v === "string" && v.trim() !== "" && !path3.isAbsolute(v)) {
771
+ out[key] = path3.resolve(configDir, v);
772
+ }
853
773
  }
854
- if (kept.size === new Set(records.map((r) => r.runId)).size) return records;
855
- return records.filter((r) => kept.has(r.runId));
856
- }
857
- function isJsonObject(value) {
858
- return typeof value === "object" && value !== null && !Array.isArray(value);
859
- }
860
- function isTestStatus(status) {
861
- return status === "pass" || status === "fail" || status === "skip" || status === "error";
862
- }
863
- function isOptionalString(value) {
864
- return value === void 0 || typeof value === "string";
865
- }
866
- function isTestResult(result) {
867
- return isJsonObject(result) && typeof result.testId === "string" && typeof result.suite === "string" && typeof result.name === "string" && isTestStatus(result.status) && (result.durationMs === null || Number.isFinite(result.durationMs)) && isOptionalString(result.message) && isOptionalString(result.stack) && (result.attempts === void 0 || Array.isArray(result.attempts) && result.attempts.every(isTestStatus));
868
- }
869
- function hasValidRunData(record) {
870
- return typeof record.runId === "string" && typeof record.timestamp === "string" && // Older or hand-authored history can omit execution metadata.
871
- (record.attempt === void 0 || Number.isInteger(record.attempt)) && isOptionalString(record.commitSha) && isOptionalString(record.branch) && isOptionalString(record.ciRunId) && Array.isArray(record.results) && record.results.every(isTestResult);
774
+ return out;
872
775
  }
873
- var HistoryStore = class _HistoryStore {
874
- path;
875
- warnings = [];
876
- /** Schema version read from the file header; null for legacy header-less stores. */
877
- formatVersion = null;
878
- /**
879
- * Set when `history.jsonl` exists but could not be read at all (EISDIR,
880
- * EACCES, …): the store then behaves as empty, but callers that diagnose
881
- * setup (doctor) must treat it as a hard failure, not as "0 runs".
882
- * Holds `<errno>: <message>`; null when the file was read or is absent.
883
- */
884
- unreadable = null;
885
- loaded = false;
886
- records = [];
887
- /** Content of the lock file this instance wrote; release only removes a lock that still matches. */
888
- lockToken = null;
889
- constructor(storeDir) {
890
- this.path = path3.join(storeDir, "history.jsonl");
776
+ function readConfigFile(file) {
777
+ const abs = path3.resolve(file);
778
+ let raw;
779
+ try {
780
+ raw = readFileSync3(abs, "utf8");
781
+ } catch (err) {
782
+ throw new Error(`cannot read config ${abs}: ${err.message}`);
783
+ }
784
+ let parsed;
785
+ try {
786
+ parsed = JSON.parse(stripJsonComments(raw.replace(/^\uFEFF/, "")));
787
+ } catch (err) {
788
+ throw new Error(`invalid config in ${abs}: ${err.message}`);
891
789
  }
892
- /**
893
- * Record a warning on this instance and tell any subscribers. Callers that
894
- * never see the instance — `run` goes through runLive, which keeps its
895
- * store private — subscribe instead of losing e.g. "prune skipped".
896
- */
897
- warn(message, first = false) {
898
- if (first) this.warnings.unshift(message);
899
- else this.warnings.push(message);
900
- for (const listener of warningListeners) listener(message);
790
+ if (parsed === null || typeof parsed !== "object" || Array.isArray(parsed)) {
791
+ throw new Error(
792
+ `invalid config in ${abs}: config must be a JSON object, got ${describe(parsed)}`
793
+ );
901
794
  }
902
- ensureStoreDir() {
903
- mkdirSync(path3.dirname(this.path), { recursive: true });
795
+ return anchorConfigPaths(parsed, path3.dirname(abs));
796
+ }
797
+ function loadConfig(cwd) {
798
+ let dir = path3.resolve(cwd);
799
+ for (let depth = 0; depth <= 3; depth++) {
800
+ const candidate = path3.join(dir, CONFIG_FILE_NAME);
801
+ if (existsSync3(candidate)) {
802
+ return { config: readConfigFile(candidate), path: candidate };
803
+ }
804
+ const parent = path3.dirname(dir);
805
+ if (parent === dir) break;
806
+ dir = parent;
904
807
  }
905
- ensureLoaded() {
906
- if (this.loaded) return;
907
- this.loaded = true;
908
- if (!existsSync3(this.path)) return;
909
- let raw;
808
+ return { config: {}, path: null };
809
+ }
810
+ function detectRunner(cwd) {
811
+ const has = (f) => {
910
812
  try {
911
- raw = readFileSync3(this.path, "utf8");
912
- } catch (err) {
913
- const e = err;
914
- const code = e.code ?? "error";
915
- this.unreadable = e.message.startsWith(code) ? e.message : `${code}: ${e.message}`;
916
- this.warn(`history store unreadable (${code}): ${this.path}`);
917
- return;
918
- }
919
- let start = 0;
920
- let lineNo = 0;
921
- while (start < raw.length) {
922
- let end = raw.indexOf("\n", start);
923
- if (end === -1) end = raw.length;
924
- const line = raw.slice(start, end).trim();
925
- lineNo++;
926
- this.processLine(line, lineNo);
927
- start = end + 1;
928
- }
929
- if (this.formatVersion !== null && this.formatVersion > STORE_FORMAT_VERSION) {
930
- this.warn(
931
- `store format v${this.formatVersion} is newer than this flakefinder (v${STORE_FORMAT_VERSION}) \u2014 unknown fields will be preserved`,
932
- true
933
- );
813
+ statSync2(path3.join(cwd, f));
814
+ return true;
815
+ } catch {
816
+ return false;
934
817
  }
935
- }
936
- processLine(line, i) {
937
- if (!line) return;
938
- let parsed;
818
+ };
819
+ if (has("package.json")) {
939
820
  try {
940
- parsed = JSON.parse(line);
821
+ const pkg = JSON.parse(readFileSync3(path3.join(cwd, "package.json"), "utf8"));
822
+ const deps = { ...pkg.dependencies, ...pkg.devDependencies };
823
+ const scripts = JSON.stringify(pkg.scripts ?? {});
824
+ if (deps.jest || deps.vitest || /\b(jest|vitest)\b/.test(scripts)) return "jest";
825
+ if (deps.mocha || /\bmocha\b/.test(scripts)) return "mocha";
941
826
  } catch {
942
- if (this.warnings.length < 10) {
943
- this.warn(`skipping corrupt line ${i} in ${this.path}`);
944
- }
945
- return;
946
827
  }
947
- if (!isJsonObject(parsed)) {
948
- if (this.warnings.length < 10) {
949
- this.warn(`skipping record-shaped garbage at line ${i} in ${this.path}`);
950
- }
951
- return;
828
+ }
829
+ if (has("pyproject.toml") || has("pytest.ini") || has("setup.py") || has("setup.cfg"))
830
+ return "pytest";
831
+ if (has(".mocharc.yml") || has(".mocharc.json") || has(".mocharc.js") || has(".mocharc.cjs"))
832
+ return "mocha";
833
+ if (has("go.mod")) return "go";
834
+ return "generic";
835
+ }
836
+
837
+ // src/doctor.ts
838
+ import { spawnSync } from "child_process";
839
+ import { existsSync as existsSync5, statSync as statSync4 } from "fs";
840
+ import path6 from "path";
841
+
842
+ // src/quarantine/manager.ts
843
+ import { existsSync as existsSync4, linkSync as linkSync2, readFileSync as readFileSync4, rmSync as rmSync2, statSync as statSync3, writeFileSync as writeFileSync3 } from "fs";
844
+ import path4 from "path";
845
+
846
+ // src/runner/adapters.ts
847
+ function escapeRegExp(s) {
848
+ return s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
849
+ }
850
+ function titleAlternation(names) {
851
+ const alts = names.map((n) => escapeRegExp(n.trim()).replace(/ > /g, "(?: > | )"));
852
+ return [...new Set(alts)].join("|");
853
+ }
854
+ function failedNamesOf(records) {
855
+ const names = /* @__PURE__ */ new Set();
856
+ for (const r of records) {
857
+ for (const t of r.results) {
858
+ if (t.status === "fail" || t.status === "error") names.add(t.name);
952
859
  }
953
- if (parsed.runId === void 0 && parsed.results === void 0) {
954
- if (typeof parsed.version === "number") {
955
- if (i === 1) this.formatVersion = parsed.version;
956
- else if (this.warnings.length < 10) {
957
- this.warn(`unexpected schema marker at line ${i} \u2014 skipped`);
958
- }
959
- return;
960
- }
961
- if (this.warnings.length < 10) {
962
- this.warn(`skipping record-shaped garbage at line ${i} in ${this.path}`);
963
- }
964
- return;
860
+ }
861
+ return [...names];
862
+ }
863
+ function failedOnlyArgs(runner, failedNames, quarantinedNames = []) {
864
+ if (failedNames.length === 0) return null;
865
+ switch (runner) {
866
+ case "jest":
867
+ case "mocha": {
868
+ const include = titleAlternation(failedNames);
869
+ const exclude = titleAlternation(quarantinedNames);
870
+ const pattern = exclude !== "" ? `^(?=(?:.* )?(?:${include})\\s*$)(?!(?:.* )?(?:${exclude})\\s*$)` : `^(?:.* )?(?:${include})\\s*$`;
871
+ return runner === "jest" ? ["-t", pattern] : ["--grep", pattern];
965
872
  }
966
- if (!hasValidRunData(parsed)) {
967
- if (this.warnings.length < 10) {
968
- this.warn(`skipping invalid record at line ${i} in ${this.path}`);
969
- }
970
- return;
873
+ case "go": {
874
+ const parents = new Set(failedNames.map((n) => n.includes("/") ? n.split("/")[0] : n));
875
+ const pattern = `^(${[...parents].map(escapeRegExp).join("|")})$`;
876
+ return ["-run", pattern];
971
877
  }
972
- parsed.attempt ??= 1;
973
- this.records.push(parsed);
878
+ case "pytest":
879
+ return ["--lf"];
880
+ default:
881
+ return null;
974
882
  }
975
- /** Append one complete line even if a prior write ended before its newline. */
976
- appendLine(run) {
977
- const line = JSON.stringify(run);
978
- const fd = openSync(this.path, "a+");
979
- try {
980
- const size = fstatSync(fd).size;
981
- let prefix = "";
982
- if (size === 0) {
983
- prefix = `${JSON.stringify({ version: STORE_FORMAT_VERSION })}
984
- `;
985
- } else {
986
- const tail = Buffer.alloc(1);
987
- readSync(fd, tail, 0, 1, size - 1);
988
- if (tail[0] !== 10) prefix = "\n";
883
+ }
884
+
885
+ // src/quarantine/manager.ts
886
+ function ambiguousQuarantineName(names, runs) {
887
+ const selected = new Set(names);
888
+ const sources = /* @__PURE__ */ new Map();
889
+ for (const run of runs) {
890
+ for (const result of run.results) {
891
+ if (result.file === void 0 && result.reportScope === void 0 || !selected.has(result.name)) {
892
+ continue;
989
893
  }
990
- writeFileSync2(fd, `${prefix}${line}
991
- `, "utf8");
992
- if (size === 0) this.formatVersion = STORE_FORMAT_VERSION;
993
- } finally {
994
- closeSync(fd);
894
+ const source = JSON.stringify([result.file, result.reportScope]);
895
+ const previous = sources.get(result.name);
896
+ if (previous !== void 0 && previous !== source) return result.name;
897
+ sources.set(result.name, source);
995
898
  }
996
899
  }
997
- get lockPath() {
998
- return `${this.path}.lock`;
900
+ return void 0;
901
+ }
902
+ var EMPTY = { version: 1, entries: [] };
903
+ function applyOp(entries, op) {
904
+ if (op.kind === "remove") return entries.filter((e) => e.testId !== op.testId);
905
+ if (op.kind === "prune") {
906
+ return entries.filter((e) => e.testId !== op.testId || e.quarantinedAt !== op.quarantinedAt);
999
907
  }
1000
- /**
1001
- * Advisory lock around writes (append/prune). Two CI matrix shards writing
1002
- * multi-KB records can interleave in one append and corrupt a line — the
1003
- * lock serializes them. Busy-waits in ≤50 ms slices (Atomics.wait) up to 2 s
1004
- * before giving up with an actionable error; a lock older than 30 s is
1005
- * reclaimed only when its host/process information permits recovery.
1006
- *
1007
- * The lock file is created atomically WITH its content (write a private
1008
- * temp file, then link() it into place — link fails if the lock exists), so
1009
- * competitors never see a half-written lock. Empty/unparseable locks (older
1010
- * flakefinder versions, torn writes) are aged by mtime, and stale locks are
1011
- * reclaimed one waiter at a time (breakStaleLock).
1012
- */
1013
- acquireLock() {
1014
- const deadline = Date.now() + 2e3;
1015
- for (; ; ) {
1016
- if (this.tryCreateLock()) return;
1017
- if (Date.now() >= deadline) {
1018
- throw new StoreBusyError(
1019
- `history store is busy (held by another flakefinder process for >2s): ${this.lockPath}. Run ingest steps serially, or give each CI shard its own storeDir. If the writer stopped on another host or during lock recovery, verify all writers have stopped before removing the abandoned lock and its .recover-* file.`
1020
- );
1021
- }
1022
- let content;
1023
- try {
1024
- content = readFileSync3(this.lockPath, "utf8");
1025
- } catch (err) {
1026
- const code = err.code;
1027
- if (code === "ENOENT") continue;
1028
- throw this.lockError(code, "exists but cannot be read as a lock file");
1029
- }
1030
- const ageMs = lockAgeMs(this.lockPath, content);
1031
- if (ageMs === null) continue;
1032
- if (ageMs > LOCK_STALE_MS2 && breakStaleLock2(this.lockPath, content)) continue;
1033
- Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, 50);
908
+ const prior = entries.find((e) => e.testId === op.entry.testId);
909
+ const entry = prior?.quarantinedAt ? { ...op.entry, quarantinedAt: prior.quarantinedAt } : op.entry;
910
+ return [...entries.filter((e) => e.testId !== op.entry.testId), entry];
911
+ }
912
+ var LOCK_TIMEOUT_MS = 1e4;
913
+ var LOCK_STALE_MS2 = 3e4;
914
+ function sleepSync2(ms) {
915
+ Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms);
916
+ }
917
+ function lockPid(content) {
918
+ try {
919
+ const parsed = JSON.parse(content);
920
+ if (typeof parsed === "object" && parsed !== null && typeof parsed.pid === "number") {
921
+ return parsed.pid;
1034
922
  }
923
+ } catch {
1035
924
  }
1036
- lockError(code, what) {
1037
- return new Error(
1038
- `history store lock ${this.lockPath} ${what} (${code ?? "error"}) \u2014 check that the store directory is writable and that the lock path is not a directory`
1039
- );
925
+ return Number.parseInt(content, 10);
926
+ }
927
+ function removeQuietly(target) {
928
+ try {
929
+ rmSync2(target, { force: true });
930
+ return true;
931
+ } catch {
932
+ return false;
1040
933
  }
1041
- /**
1042
- * One attempt to take the lock: true on success, false ONLY when another
1043
- * process holds it (EEXIST). Anything else — read-only directory (EACCES,
1044
- * EROFS), missing dir, … — throws: retrying cannot fix it, and treating it
1045
- * as "held" used to spin forever.
1046
- */
1047
- tryCreateLock() {
1048
- const token = JSON.stringify({
1049
- pid: process.pid,
1050
- host: hostname(),
1051
- epoch: Date.now(),
1052
- nonce: randomBytes(6).toString("hex")
1053
- });
1054
- const tmp = `${this.lockPath}.${uniqueSuffix()}.tmp`;
1055
- try {
1056
- writeFileSync2(tmp, token, "utf8");
1057
- } catch (err) {
1058
- throw this.lockError(err.code, "cannot be created");
1059
- }
934
+ }
935
+ function removePartialLock(lockPath, token) {
936
+ try {
937
+ const content = readFileSync4(lockPath, "utf8");
938
+ if (content !== "" && !token.startsWith(content)) return;
939
+ } catch {
940
+ return;
941
+ }
942
+ removeQuietly(lockPath);
943
+ }
944
+ function tryCreateLock(lockPath) {
945
+ const token = JSON.stringify({
946
+ pid: process.pid,
947
+ epoch: Date.now(),
948
+ nonce: `${Date.now().toString(36)}${Math.random().toString(36).slice(2, 8)}`
949
+ });
950
+ const tmp = `${lockPath}.${process.pid}.${Date.now().toString(36)}.${Math.random().toString(36).slice(2, 8)}.tmp`;
951
+ try {
952
+ writeFileSync3(tmp, token, "utf8");
1060
953
  try {
1061
- linkSync2(tmp, this.lockPath);
1062
- this.lockToken = token;
1063
- return true;
954
+ linkSync2(tmp, lockPath);
955
+ return token;
1064
956
  } catch (err) {
1065
957
  const code = err.code;
1066
- if (code === "EEXIST") return false;
958
+ if (code === "EEXIST") return null;
1067
959
  try {
1068
- writeFileSync2(this.lockPath, token, { flag: "wx" });
1069
- this.lockToken = token;
1070
- return true;
1071
- } catch (err2) {
1072
- const code2 = err2.code;
1073
- if (code2 === "EEXIST") return false;
1074
- throw this.lockError(code2, "cannot be created");
960
+ writeFileSync3(lockPath, token, { flag: "wx" });
961
+ } catch (fallbackErr) {
962
+ if (fallbackErr.code === "EEXIST") return null;
963
+ removePartialLock(lockPath, token);
964
+ throw fallbackErr;
1075
965
  }
1076
- } finally {
1077
- rmSync2(tmp, { force: true });
966
+ try {
967
+ if (readFileSync4(lockPath, "utf8") !== token) return null;
968
+ } catch {
969
+ return null;
970
+ }
971
+ return token;
1078
972
  }
973
+ } finally {
974
+ removeQuietly(tmp);
1079
975
  }
1080
- releaseLock() {
1081
- const token = this.lockToken;
1082
- this.lockToken = null;
976
+ }
977
+ function processAlive(pid) {
978
+ try {
979
+ process.kill(pid, 0);
980
+ return true;
981
+ } catch (err) {
982
+ const code = err.code;
983
+ return code !== "ESRCH" && code !== "EINVAL" && code !== "ERANGE" && code !== "ERR_INVALID_ARG_TYPE" && code !== "ERR_OUT_OF_RANGE";
984
+ }
985
+ }
986
+ function contentIsStale(content, ageMs) {
987
+ const pid = lockPid(content);
988
+ if (Number.isInteger(pid) && pid > 0) {
989
+ return pid === process.pid || !processAlive(pid);
990
+ }
991
+ return ageMs > LOCK_STALE_MS2;
992
+ }
993
+ function lockState(lockPath) {
994
+ let content;
995
+ let mtimeMs;
996
+ try {
997
+ content = readFileSync4(lockPath, "utf8");
998
+ mtimeMs = statSync3(lockPath).mtimeMs;
999
+ } catch (err) {
1000
+ const code = err.code;
1001
+ if (code === "ENOENT") return { state: "missing" };
1002
+ if (code === "EPERM" || code === "EBUSY" || code === "EACCES") return { state: "live" };
1003
+ throw new Error(
1004
+ `quarantine lock ${lockPath} exists but cannot be read as a lock file (${code ?? "error"}) \u2014 check that the quarantine directory is writable and that the lock path is not a directory`
1005
+ );
1006
+ }
1007
+ return contentIsStale(content, Date.now() - mtimeMs) ? { state: "stale", content } : { state: "live" };
1008
+ }
1009
+ function tryTakeBreaker(breakPath) {
1010
+ for (let attempt = 0; attempt < 2; attempt++) {
1011
+ const token = tryCreateLock(breakPath);
1012
+ if (token !== null) return token;
1083
1013
  try {
1084
- if (readFileSync3(this.lockPath, "utf8") === token) rmSync2(this.lockPath, { force: true });
1014
+ const content = readFileSync4(breakPath, "utf8");
1015
+ const age = Date.now() - statSync3(breakPath).mtimeMs;
1016
+ if (contentIsStale(content, age)) {
1017
+ if (!removeQuietly(breakPath)) return null;
1018
+ continue;
1019
+ }
1085
1020
  } catch {
1086
1021
  }
1022
+ return null;
1087
1023
  }
1088
- loadAll() {
1089
- this.ensureLoaded();
1090
- return [...this.records];
1091
- }
1092
- runs() {
1093
- this.ensureLoaded();
1094
- return [...this.records];
1024
+ return null;
1025
+ }
1026
+ function breakStaleLock2(lockPath, observed) {
1027
+ const breakPath = `${lockPath}.break`;
1028
+ const breakerToken = tryTakeBreaker(breakPath);
1029
+ if (breakerToken === null) return false;
1030
+ try {
1031
+ let content;
1032
+ let mtimeMs;
1033
+ try {
1034
+ content = readFileSync4(lockPath, "utf8");
1035
+ mtimeMs = statSync3(lockPath).mtimeMs;
1036
+ } catch {
1037
+ return false;
1038
+ }
1039
+ if (content !== observed || !contentIsStale(content, Date.now() - mtimeMs)) return false;
1040
+ return removeQuietly(lockPath);
1041
+ } finally {
1042
+ try {
1043
+ if (readFileSync4(breakPath, "utf8") === breakerToken) removeQuietly(breakPath);
1044
+ } catch {
1045
+ }
1095
1046
  }
1096
- /**
1097
- * Write paths must not surface raw EISDIR/EACCES: a directory (or other
1098
- * non-file) at the store path is a setup error that should name the file.
1099
- */
1100
- assertWritableFile() {
1101
- if (existsSync3(this.path) && !statSync3(this.path).isFile()) {
1047
+ }
1048
+ function withFileLock(target, fn) {
1049
+ const lockPath = `${target}.lock`;
1050
+ const deadline = Date.now() + LOCK_TIMEOUT_MS;
1051
+ let token;
1052
+ for (; ; ) {
1053
+ const acquired = tryCreateLock(lockPath);
1054
+ if (acquired !== null) {
1055
+ token = acquired;
1056
+ break;
1057
+ }
1058
+ if (Date.now() > deadline) {
1102
1059
  throw new Error(
1103
- `history store ${this.path} exists but is not a regular file \u2014 delete or rename it (flakefinder recreates it on the next write)`
1060
+ `quarantine file is locked by another flakefinder process (${lockPath}) \u2014 delete the lock if no other flakefinder is running`
1104
1061
  );
1105
1062
  }
1063
+ const state = lockState(lockPath);
1064
+ if (state.state === "missing") continue;
1065
+ if (state.state === "stale") {
1066
+ if (!breakStaleLock2(lockPath, state.content)) {
1067
+ sleepSync2(5 + Math.floor(Math.random() * 15));
1068
+ }
1069
+ continue;
1070
+ }
1071
+ sleepSync2(10 + Math.floor(Math.random() * 20));
1106
1072
  }
1107
- /**
1108
- * Appends without reading the store: when this instance has not loaded the
1109
- * file yet, the record simply becomes part of the next (lazy) read.
1110
- */
1111
- append(run) {
1112
- this.ensureStoreDir();
1113
- this.assertWritableFile();
1114
- this.acquireLock();
1073
+ try {
1074
+ return fn();
1075
+ } finally {
1115
1076
  try {
1116
- try {
1117
- this.appendLine(run);
1118
- } catch (err) {
1119
- const e = err;
1120
- throw new Error(
1121
- `cannot write history store ${this.path} (${e.code ?? "error"}) \u2014 check it is a writable regular file`
1122
- );
1077
+ const current = readFileSync4(lockPath, "utf8");
1078
+ const ours = current === token;
1079
+ if (ours) {
1080
+ rmSync2(lockPath, { force: true });
1123
1081
  }
1124
- if (this.loaded) this.records.push(run);
1125
- } finally {
1126
- this.releaseLock();
1082
+ } catch {
1127
1083
  }
1128
1084
  }
1129
- /**
1130
- * Keep only the last `maxRuns` RUNS (distinct runIds — one `run` with
1131
- * retries writes one record per attempt, all sharing a runId, and they are
1132
- * kept or dropped together); rewrite the file atomically.
1133
- * Re-reads the file FRESH inside the lock: a stale in-memory snapshot
1134
- * would silently delete records another process appended between our load
1135
- * and this prune (verified 10/10 with two concurrent ingests before the
1136
- * fix). In-memory records are resynced to the fresh state — including an
1137
- * empty one: the stale view is only kept when the fresh read FAILED, and
1138
- * then nothing is rewritten.
1139
- */
1140
- prune(maxRuns) {
1141
- if (this.unreadable) return;
1142
- if (!existsSync3(this.path)) return;
1143
- this.ensureStoreDir();
1085
+ }
1086
+ var QuarantineManager = class {
1087
+ filePath;
1088
+ file;
1089
+ pending = [];
1090
+ constructor(filePath) {
1091
+ this.filePath = filePath;
1092
+ this.file = this.load();
1093
+ }
1094
+ load() {
1095
+ if (!existsSync4(this.filePath)) return { ...EMPTY, entries: [] };
1144
1096
  try {
1145
- this.acquireLock();
1097
+ const parsed = JSON.parse(readFileSync4(this.filePath, "utf8"));
1098
+ if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) {
1099
+ throw new Error("expected a JSON object");
1100
+ }
1101
+ const obj = parsed;
1102
+ if (!Array.isArray(obj.entries)) throw new Error('missing "entries" array');
1103
+ obj.entries.forEach((e, i) => {
1104
+ if (typeof e !== "object" || e === null || Array.isArray(e)) {
1105
+ throw new Error(`entry #${i + 1} is not an object`);
1106
+ }
1107
+ for (const field of ["testId", "suite", "name"]) {
1108
+ const value = e[field];
1109
+ if (typeof value !== "string" || value === "") {
1110
+ throw new Error(`entry #${i + 1} has no string "${field}"`);
1111
+ }
1112
+ }
1113
+ });
1114
+ return { ...obj, version: 1, entries: obj.entries };
1146
1115
  } catch (err) {
1147
- if (!(err instanceof StoreBusyError)) throw err;
1148
- this.warn(`history store busy \u2014 prune skipped this time: ${this.path}`);
1149
- return;
1116
+ throw new Error(`invalid quarantine file ${this.filePath}: ${err.message}`);
1150
1117
  }
1151
- try {
1152
- const fresh = new _HistoryStore(path3.dirname(this.path));
1153
- const source = fresh.runs();
1154
- if (fresh.unreadable !== null) {
1155
- if (this.loaded) {
1156
- this.warn(`history store unreadable during prune \u2014 not pruned: ${this.path}`);
1157
- } else {
1158
- this.adopt(fresh);
1118
+ }
1119
+ apply(op) {
1120
+ this.pending.push(op);
1121
+ this.file.entries = applyOp(this.file.entries, op);
1122
+ }
1123
+ list() {
1124
+ return [...this.file.entries];
1125
+ }
1126
+ /** Add or replace an entry (same testId); a re-add keeps the original quarantinedAt. */
1127
+ add(entry) {
1128
+ this.apply({ kind: "add", entry });
1129
+ }
1130
+ remove(testId) {
1131
+ const existed = this.file.entries.some((e) => e.testId === testId);
1132
+ if (existed) this.apply({ kind: "remove", testId });
1133
+ return existed;
1134
+ }
1135
+ /**
1136
+ * Drop entries that no longer deserve quarantine. Deliberately
1137
+ * conservative: quarantined tests are excluded from runs, so "not seen
1138
+ * lately" is NOT evidence of health (that would silently un-quarantine
1139
+ * everything). An entry leaves quarantine only on positive evidence —
1140
+ * the test ran (quarantine disabled or full-suite run) since it was
1141
+ * quarantined and passed stably — or when the entry is older than 90 days and the test is gone from
1142
+ * history. Returns the removed entries.
1143
+ */
1144
+ prune(verdicts, runs = [], maxAgeDays = 90) {
1145
+ if (verdicts.length === 0) return [];
1146
+ const byId = new Map(verdicts.map((v) => [v.testId, v]));
1147
+ const latestPass = /* @__PURE__ */ new Map();
1148
+ for (const run of runs) {
1149
+ const time = Date.parse(run.timestamp);
1150
+ for (const test of run.results) {
1151
+ if (test.status === "pass" && time > (latestPass.get(test.testId) ?? -Infinity)) {
1152
+ latestPass.set(test.testId, time);
1159
1153
  }
1160
- return;
1161
- }
1162
- const keep = lastRuns(source, maxRuns);
1163
- if (keep.length === source.length) {
1164
- this.adopt(fresh);
1165
- return;
1166
1154
  }
1167
- const version = Math.max(fresh.formatVersion ?? STORE_FORMAT_VERSION, STORE_FORMAT_VERSION);
1168
- const tmp = `${this.path}.tmp`;
1169
- const fd = openSync(tmp, "w");
1155
+ }
1156
+ const removed = [];
1157
+ for (const entry of this.file.entries) {
1158
+ const v = byId.get(entry.testId);
1159
+ const quarantinedMs = Date.parse(entry.quarantinedAt);
1160
+ const passedAt = v?.lastStatus === "pass" ? Date.parse(v.lastSeen) : latestPass.get(entry.testId);
1161
+ const healthy = v?.classification === "passing" && v.runsObserved >= 10 && passedAt !== void 0 && passedAt >= quarantinedMs;
1162
+ const agedOut = v?.classification === "gone" && !Number.isNaN(quarantinedMs) && Date.now() - quarantinedMs > maxAgeDays * 864e5;
1163
+ if (healthy || agedOut) removed.push(entry);
1164
+ }
1165
+ for (const { testId, quarantinedAt } of removed)
1166
+ this.apply({ kind: "prune", testId, quarantinedAt });
1167
+ return removed;
1168
+ }
1169
+ /**
1170
+ * Persist this manager's changes. Under the lockfile: re-read the file
1171
+ * (another process may have saved since our constructor ran), replay our
1172
+ * pending operations onto it, then write atomically — a temp file in the
1173
+ * same directory renamed over the target, so neither a crash nor a
1174
+ * concurrent reader ever sees a torn file.
1175
+ */
1176
+ save() {
1177
+ withFileLock(this.filePath, () => {
1178
+ const fresh = this.load();
1179
+ for (const op of this.pending) fresh.entries = applyOp(fresh.entries, op);
1180
+ const tmp = `${this.filePath}.${process.pid}.${Date.now().toString(36)}.tmp`;
1170
1181
  try {
1171
- writeFileSync2(fd, `${JSON.stringify({ version })}
1172
- `, "utf8");
1173
- for (const r of keep) writeFileSync2(fd, `${JSON.stringify(r)}
1182
+ writeFileSync3(tmp, `${JSON.stringify(fresh, null, 2)}
1174
1183
  `, "utf8");
1175
- } finally {
1176
- closeSync(fd);
1184
+ renameOverSync(tmp, this.filePath);
1185
+ } catch (err) {
1186
+ rmSync2(tmp, { force: true });
1187
+ throw err;
1188
+ }
1189
+ this.file = fresh;
1190
+ this.pending = [];
1191
+ });
1192
+ }
1193
+ };
1194
+ var ROOT_MARKERS = ["pytest.ini", "pyproject.toml", "tox.ini", "setup.cfg", "setup.py", ".git"];
1195
+ function existsUpward(cwd, rel) {
1196
+ let dir = path4.resolve(cwd);
1197
+ for (; ; ) {
1198
+ if (existsSync4(path4.join(dir, rel))) return true;
1199
+ const parent = path4.dirname(dir);
1200
+ if (parent === dir || ROOT_MARKERS.some((m) => existsSync4(path4.join(dir, m)))) return false;
1201
+ dir = parent;
1202
+ }
1203
+ }
1204
+ function pytestNodeId(suite, name, cwd) {
1205
+ if (/[\\/]|::|\.py$/.test(suite)) return `${suite.replace(/\\/g, "/")}::${name}`;
1206
+ const parts = suite.split(".").filter((p) => p !== "");
1207
+ if (parts.length === 0) return name;
1208
+ let moduleEnd = 0;
1209
+ if (cwd !== void 0) {
1210
+ for (let i = parts.length; i >= 1; i--) {
1211
+ if (existsUpward(cwd, `${parts.slice(0, i).join("/")}.py`)) {
1212
+ moduleEnd = i;
1213
+ break;
1177
1214
  }
1178
- renameOverSync(tmp, this.path);
1179
- this.adopt(fresh);
1180
- this.records = keep;
1181
- this.formatVersion = version;
1182
- } finally {
1183
- this.releaseLock();
1184
1215
  }
1185
1216
  }
1186
- /** Resync this instance's view to a fresh read of the same store. */
1187
- adopt(fresh) {
1188
- if (!this.loaded) this.warnings.push(...fresh.warnings);
1189
- this.loaded = true;
1190
- this.records = fresh.runs();
1191
- this.formatVersion = fresh.formatVersion;
1192
- this.unreadable = fresh.unreadable;
1217
+ if (moduleEnd === 0) {
1218
+ moduleEnd = 1;
1219
+ for (let i = parts.length - 1; i >= 1; i--) {
1220
+ if (!/^[A-Z]/.test(parts[i])) {
1221
+ moduleEnd = i + 1;
1222
+ break;
1223
+ }
1224
+ }
1193
1225
  }
1194
- };
1226
+ const file = `${parts.slice(0, moduleEnd).join("/")}.py`;
1227
+ return [file, ...parts.slice(moduleEnd), name].join("::");
1228
+ }
1229
+ function exclusionArgs(runner, entries, cwd) {
1230
+ if (entries.length === 0) return [];
1231
+ switch (runner) {
1232
+ case "pytest": {
1233
+ const args = [];
1234
+ for (const e of entries) args.push("--deselect", pytestNodeId(e.suite, e.name, cwd));
1235
+ return args;
1236
+ }
1237
+ case "jest":
1238
+ case "mocha": {
1239
+ const flag = runner === "jest" ? "-t" : "--grep";
1240
+ return [flag, `^(?!(?:.* )?(?:${titleAlternation(entries.map((e) => e.name))})\\s*$)`];
1241
+ }
1242
+ // go / generic: no per-test exclusion — callers must warn
1243
+ default:
1244
+ return [];
1245
+ }
1246
+ }
1247
+ var PYTEST_EXACT_PLUGIN_MODULE = "flakefinder_exact_deselect";
1248
+ var PYTEST_EXACT_ENV = "FLAKEFINDER_EXACT_DESELECT";
1249
+ var PYTEST_EXACT_PLUGIN_SOURCE = `# Generated by flakefinder: exact quarantine deselection (temporary file).
1250
+ import json
1251
+ import os
1252
+
1253
+ import pytest
1254
+
1255
+
1256
+ @pytest.hookimpl(tryfirst=True)
1257
+ def pytest_collection_modifyitems(config, items):
1258
+ try:
1259
+ ours = json.loads(os.environ.get("${PYTEST_EXACT_ENV}", "[]"))
1260
+ except ValueError:
1261
+ return
1262
+ if not isinstance(ours, list) or not ours:
1263
+ return
1264
+ remaining = list(config.getoption("deselect") or [])
1265
+ for node_id in ours:
1266
+ if node_id in remaining:
1267
+ remaining.remove(node_id)
1268
+ config.option.deselect = remaining
1269
+ exact = set(ours)
1270
+ keep, drop = [], []
1271
+ for item in items:
1272
+ nid = item.nodeid
1273
+ base = nid.split("[", 1)[0]
1274
+ (drop if nid in exact or base in exact else keep).append(item)
1275
+ if drop:
1276
+ config.hook.pytest_deselected(items=drop)
1277
+ items[:] = keep
1278
+ `;
1279
+ function pytestExactDeselectEnv(nodeIds, pluginDir, env = process.env) {
1280
+ const plugins = (env.PYTEST_PLUGINS ?? "").split(",").map((p) => p.trim()).filter((p) => p !== "" && p !== PYTEST_EXACT_PLUGIN_MODULE);
1281
+ const pythonPath = env.PYTHONPATH ? `${pluginDir}${path4.delimiter}${env.PYTHONPATH}` : pluginDir;
1282
+ return {
1283
+ ...env,
1284
+ PYTEST_PLUGINS: [...plugins, PYTEST_EXACT_PLUGIN_MODULE].join(","),
1285
+ PYTHONPATH: pythonPath,
1286
+ [PYTEST_EXACT_ENV]: JSON.stringify(nodeIds)
1287
+ };
1288
+ }
1289
+ function deselectedNodeIds(args) {
1290
+ const ids = [];
1291
+ for (let i = 0; i < args.length - 1; i++) if (args[i] === "--deselect") ids.push(args[i + 1]);
1292
+ return ids;
1293
+ }
1195
1294
 
1196
1295
  // src/util/glob.ts
1197
1296
  import { readdirSync } from "fs";
1198
- import path4 from "path";
1297
+ import path5 from "path";
1199
1298
  var SKIP_DIRS = /* @__PURE__ */ new Set(["node_modules", ".git", "dist", "coverage"]);
1200
1299
  function globToRegExp(pattern, caseInsensitive) {
1201
1300
  const parts = pattern.split("/").filter((p) => p.length > 0);
@@ -1219,13 +1318,19 @@ function globToRegExp(pattern, caseInsensitive) {
1219
1318
  if (!re.endsWith("$")) re += "$";
1220
1319
  return new RegExp(re, caseInsensitive ? "i" : void 0);
1221
1320
  }
1321
+ function normalizeGlob(pattern) {
1322
+ const posix = pattern.replace(/\\/g, "/").replace(/^\.\//, "");
1323
+ return posix.includes("/") ? posix : `**/${posix}`;
1324
+ }
1325
+ function matchesReportGlob(relativePath, pattern) {
1326
+ return globToRegExp(normalizeGlob(pattern), process.platform === "win32").test(
1327
+ relativePath.replace(/\\/g, "/")
1328
+ );
1329
+ }
1222
1330
  function matchGlobs(cwd, patterns) {
1223
1331
  if (patterns.length === 0) return [];
1224
1332
  const caseInsensitive = process.platform === "win32";
1225
- const normalized = patterns.map((p) => {
1226
- const posix = p.replace(/\\/g, "/").replace(/^\.\//, "");
1227
- return posix.includes("/") ? posix : `**/${posix}`;
1228
- });
1333
+ const normalized = patterns.map(normalizeGlob);
1229
1334
  const regexps = normalized.map((p) => globToRegExp(p, caseInsensitive));
1230
1335
  const matches = /* @__PURE__ */ new Set();
1231
1336
  const walk3 = (dir, rel) => {
@@ -1240,9 +1345,9 @@ function matchGlobs(cwd, patterns) {
1240
1345
  if (entry.isDirectory()) {
1241
1346
  const name = caseInsensitive ? entry.name.toLowerCase() : entry.name;
1242
1347
  if (entry.name.startsWith(".") || SKIP_DIRS.has(name)) continue;
1243
- walk3(path4.join(dir, entry.name), relPath);
1348
+ walk3(path5.join(dir, entry.name), relPath);
1244
1349
  } else if (entry.isFile()) {
1245
- if (regexps.some((re) => re.test(relPath))) matches.add(path4.join(dir, entry.name));
1350
+ if (regexps.some((re) => re.test(relPath))) matches.add(path5.join(dir, entry.name));
1246
1351
  }
1247
1352
  }
1248
1353
  };
@@ -1256,7 +1361,7 @@ function runDoctor(cwd, opts = {}) {
1256
1361
  const lines = [];
1257
1362
  let ok = true;
1258
1363
  let config;
1259
- const explicit = opts.configPath ? path5.resolve(cwd, opts.configPath) : null;
1364
+ const explicit = opts.configPath ? path6.resolve(cwd, opts.configPath) : null;
1260
1365
  try {
1261
1366
  let configPath;
1262
1367
  if (explicit) {
@@ -1296,11 +1401,11 @@ function runDoctor(cwd, opts = {}) {
1296
1401
  } else {
1297
1402
  lines.push({
1298
1403
  status: "ok",
1299
- message: `reports: ${reportFiles.length} file(s) match (${reportFiles.slice(0, 3).map((f) => path5.basename(f)).join(", ")}${reportFiles.length > 3 ? ", \u2026" : ""})`
1404
+ message: `reports: ${reportFiles.length} file(s) match (${reportFiles.slice(0, 3).map((f) => path6.basename(f)).join(", ")}${reportFiles.length > 3 ? ", \u2026" : ""})`
1300
1405
  });
1301
1406
  }
1302
- const store = new HistoryStore(path5.resolve(cwd, config.storeDir));
1303
- if (existsSync4(store.path)) {
1407
+ const store = new HistoryStore(path6.resolve(cwd, config.storeDir));
1408
+ if (existsSync5(store.path)) {
1304
1409
  try {
1305
1410
  const runs = store.runs();
1306
1411
  if (store.unreadable !== null) {
@@ -1367,8 +1472,8 @@ function runDoctor(cwd, opts = {}) {
1367
1472
  } catch {
1368
1473
  lines.push({ status: "warn", message: "git: could not check" });
1369
1474
  }
1370
- const qPath = path5.resolve(cwd, config.quarantineFile);
1371
- if (existsSync4(qPath)) {
1475
+ const qPath = path6.resolve(cwd, config.quarantineFile);
1476
+ if (existsSync5(qPath)) {
1372
1477
  let entries;
1373
1478
  try {
1374
1479
  entries = new QuarantineManager(qPath).list();
@@ -1395,6 +1500,90 @@ function runDoctor(cwd, opts = {}) {
1395
1500
  return { lines, ok };
1396
1501
  }
1397
1502
 
1503
+ // src/util/project-results.ts
1504
+ var statusSeverity = { skip: 0, pass: 1, fail: 2, error: 3 };
1505
+ function attemptKey(record) {
1506
+ return JSON.stringify([record.runId, record.attempt]);
1507
+ }
1508
+ function groupKind(result, report) {
1509
+ if (result.playwrightProject !== void 0) return "project";
1510
+ if (report && result.file === void 0 && result.reportScope === void 0) return "fileless";
1511
+ return void 0;
1512
+ }
1513
+ function reconcileReportResults(records, warn) {
1514
+ const firstReport = /* @__PURE__ */ new Map();
1515
+ const multiple = /* @__PURE__ */ new Set();
1516
+ for (const record of records) {
1517
+ if (record.parsedFrom !== "junit" || !record.reportFile) continue;
1518
+ const attempt = attemptKey(record);
1519
+ const first = firstReport.get(attempt);
1520
+ if (first === void 0) firstReport.set(attempt, record.reportFile);
1521
+ else if (first !== record.reportFile) multiple.add(attempt);
1522
+ }
1523
+ const groups = /* @__PURE__ */ new Map();
1524
+ for (const record of records) {
1525
+ const attempt = attemptKey(record);
1526
+ const report = record.parsedFrom === "junit" && multiple.has(attempt) ? record.reportFile : void 0;
1527
+ for (const result of record.results) {
1528
+ const kind = groupKind(result, report);
1529
+ if (!kind) continue;
1530
+ const key = JSON.stringify([attempt, result.testId, kind]);
1531
+ let group = groups.get(key);
1532
+ if (!group) {
1533
+ group = { attempt, kind, results: /* @__PURE__ */ new Map() };
1534
+ groups.set(key, group);
1535
+ }
1536
+ const source = kind === "project" ? result.playwrightProject : report;
1537
+ const previous = group.results.get(source);
1538
+ if (!previous || result.status !== "skip") group.results.set(source, result);
1539
+ }
1540
+ }
1541
+ const winners = /* @__PURE__ */ new Map();
1542
+ const conflictCounts = /* @__PURE__ */ new Map();
1543
+ const affected = /* @__PURE__ */ new Set();
1544
+ for (const [key, group] of groups) {
1545
+ if (group.results.size < 2) continue;
1546
+ let winner;
1547
+ let conflict = false;
1548
+ for (const result of group.results.values()) {
1549
+ if (winner && winner.status !== result.status) conflict = true;
1550
+ if (!winner || statusSeverity[result.status] > statusSeverity[winner.status]) winner = result;
1551
+ }
1552
+ if (!winner || group.kind === "fileless" && !conflict) continue;
1553
+ winners.set(key, winner);
1554
+ affected.add(group.attempt);
1555
+ if (group.kind === "fileless" && warn) {
1556
+ conflictCounts.set(group.attempt, (conflictCounts.get(group.attempt) ?? 0) + 1);
1557
+ }
1558
+ }
1559
+ for (const [attempt, count] of conflictCounts) {
1560
+ const [runId, attemptNumber] = JSON.parse(attempt);
1561
+ warn?.(
1562
+ `run ${JSON.stringify(runId)} attempt ${attemptNumber}: ${count} test identit${count === 1 ? "y has" : "ies have"} conflicting rows across JUnit reports without file information. Kept the strongest result. Add file paths or distinct reportScopes.`
1563
+ );
1564
+ }
1565
+ if (winners.size === 0) return records;
1566
+ const emitted = /* @__PURE__ */ new Set();
1567
+ return records.map((record) => {
1568
+ const attempt = attemptKey(record);
1569
+ if (!affected.has(attempt)) return record;
1570
+ const report = record.parsedFrom === "junit" && multiple.has(attempt) ? record.reportFile : void 0;
1571
+ return {
1572
+ ...record,
1573
+ results: record.results.flatMap((result) => {
1574
+ const kind = groupKind(result, report);
1575
+ if (!kind) return [result];
1576
+ const key = JSON.stringify([attempt, result.testId, kind]);
1577
+ const winner = winners.get(key);
1578
+ if (!winner) return [result];
1579
+ if (emitted.has(key)) return [];
1580
+ emitted.add(key);
1581
+ return [winner];
1582
+ })
1583
+ };
1584
+ });
1585
+ }
1586
+
1398
1587
  // src/engine/stats.ts
1399
1588
  function median(values) {
1400
1589
  if (values.length === 0) return null;
@@ -1447,21 +1636,27 @@ var STATUSES = /* @__PURE__ */ new Set(["pass", "fail", "skip", "error"]);
1447
1636
  function executionStatuses(r) {
1448
1637
  if (!Array.isArray(r.attempts)) return [r.status];
1449
1638
  const statuses = r.attempts.filter((s) => STATUSES.has(s));
1639
+ if (r.reportedOutcome && statuses.length > 0) return statuses;
1450
1640
  if (statuses[statuses.length - 1] !== r.status) statuses.push(r.status);
1451
1641
  return statuses.length < 2 ? [r.status] : statuses;
1452
1642
  }
1453
- function collectHistories(sortedRuns) {
1643
+ function collectHistories(sortedRuns, warn) {
1454
1644
  const byId = /* @__PURE__ */ new Map();
1455
- for (const run of sortedRuns) {
1645
+ for (const run of reconcileReportResults(sortedRuns, warn)) {
1456
1646
  for (const r of run.results) {
1457
1647
  let h = byId.get(r.testId);
1458
1648
  if (!h) {
1459
1649
  h = { testId: r.testId, suite: r.suite, name: r.name, observations: [] };
1650
+ if (r.file !== void 0) h.file = r.file;
1651
+ if (r.reportScope !== void 0) h.reportScope = r.reportScope;
1460
1652
  byId.set(r.testId, h);
1461
1653
  }
1462
1654
  h.suite = r.suite;
1463
1655
  h.name = r.name;
1464
1656
  const statuses = executionStatuses(r);
1657
+ const aggregateStatus = r.reportedOutcome ? r.status : void 0;
1658
+ const reportedFlaky = r.reportedOutcome === "flaky" && statuses.includes("pass") && statuses.some(isFail);
1659
+ const durationIndex = aggregateStatus === void 0 ? statuses.length - 1 : statuses.lastIndexOf(aggregateStatus);
1465
1660
  statuses.forEach((status, sub) => {
1466
1661
  h.observations.push({
1467
1662
  runId: run.runId,
@@ -1470,26 +1665,33 @@ function collectHistories(sortedRuns) {
1470
1665
  attempt: run.attempt,
1471
1666
  sub,
1472
1667
  final: sub === statuses.length - 1,
1668
+ ...aggregateStatus === void 0 ? {} : { aggregateStatus, reportedFlaky },
1473
1669
  commitSha: run.commitSha,
1474
1670
  message: r.message,
1475
- // the reported duration belongs to the final execution only
1476
- durationMs: sub === statuses.length - 1 ? r.durationMs ?? void 0 : void 0
1671
+ durationMs: sub === durationIndex ? r.durationMs ?? void 0 : void 0
1477
1672
  });
1478
1673
  });
1479
1674
  }
1480
1675
  }
1481
1676
  return [...byId.values()];
1482
1677
  }
1483
- function collapsePerAttempt(nonSkip) {
1678
+ function collapsePerAttempt(observations) {
1484
1679
  const perAttempt = /* @__PURE__ */ new Map();
1485
- for (const o of nonSkip) {
1486
- perAttempt.set(`${o.runId}\0${o.attempt}\0${o.sub}`, o);
1680
+ let row = [];
1681
+ for (const o of observations) {
1682
+ if (o.sub === 0) row = [];
1683
+ if (o.status !== "skip") row.push(o);
1684
+ if (o.final && row.length > 0) {
1685
+ perAttempt.set(`${o.runId}\0${o.attempt}`, row);
1686
+ }
1487
1687
  }
1488
- return [...perAttempt.values()];
1688
+ return [...perAttempt.values()].flat();
1489
1689
  }
1490
1690
  function collapsePerRun(collapsed) {
1491
1691
  const perRun = /* @__PURE__ */ new Map();
1492
- for (const o of collapsed) perRun.set(o.runId, o);
1692
+ for (const o of collapsed) {
1693
+ perRun.set(o.runId, o.aggregateStatus === void 0 ? o : { ...o, status: o.aggregateStatus });
1694
+ }
1493
1695
  return [...perRun.values()];
1494
1696
  }
1495
1697
  function countSameShaFlips(collapsed) {
@@ -1559,7 +1761,7 @@ function recencyMultiplier(lastChangeAt) {
1559
1761
  return 0.3;
1560
1762
  }
1561
1763
  function flakeScore(opts) {
1562
- let score = Math.min(50, opts.sameShaFlips * 50);
1764
+ let score = opts.confirmed ? 50 : 0;
1563
1765
  score += Math.min(40, opts.retryRescues * 40);
1564
1766
  score += Math.min(24, opts.directionChanges * 8 * recencyMultiplier(opts.lastChangeAt));
1565
1767
  if (opts.runsObserved >= 10) score += 10;
@@ -1569,7 +1771,7 @@ function classify(opts) {
1569
1771
  const { perRun, cfg } = opts;
1570
1772
  if (!opts.seenRecently) return "gone";
1571
1773
  if (perRun.length === 0) return "skipped";
1572
- if (opts.sameShaFlips > 0) return "flaky-confirmed";
1774
+ if (opts.confirmed) return "flaky-confirmed";
1573
1775
  if (opts.retryRescues > 0) return "flaky-retry";
1574
1776
  if (opts.directionChanges >= 2 && perRun.length >= cfg.minRuns && opts.bothFamilies)
1575
1777
  return "flaky-suspected";
@@ -1595,20 +1797,20 @@ function confidenceFor(classification, perRun, executions, cfg) {
1595
1797
  }
1596
1798
  }
1597
1799
  var SLOW_RELATIVE_FLOOR_MS = 100;
1598
- function classifyAll(runs, cfg) {
1800
+ function classifyAll(runs, cfg, warn) {
1599
1801
  if (runs.length === 0) return [];
1600
1802
  const sorted = sortRuns(runs);
1601
1803
  const runOrder = [];
1602
1804
  for (const r of sorted) if (runOrder[runOrder.length - 1] !== r.runId) runOrder.push(r.runId);
1603
1805
  const recentRunIds = new Set(runOrder.slice(-GONE_AFTER_RUNS));
1604
- const histories = collectHistories(sorted);
1806
+ const histories = collectHistories(sorted, warn);
1605
1807
  const verdicts = histories.map((h) => {
1606
- const nonSkip = h.observations.filter((o) => o.status !== "skip");
1607
- const collapsed = collapsePerAttempt(nonSkip);
1808
+ const collapsed = collapsePerAttempt(h.observations);
1608
1809
  const perRun = collapsePerRun(collapsed);
1609
1810
  const lastObs = h.observations[h.observations.length - 1];
1610
1811
  const sameShaFlips = countSameShaFlips(collapsed);
1611
1812
  const retryRescues = countRetryRescues(collapsed);
1813
+ const confirmed = sameShaFlips > 0 || retryRescues === 0 && collapsed.some((o) => o.reportedFlaky);
1612
1814
  const dc = directionChanges(collapsed);
1613
1815
  const seenRecently = h.observations.some((o) => recentRunIds.has(o.runId));
1614
1816
  const bothFamilies = collapsed.some((o) => isFail(o.status)) && collapsed.some((o) => !isFail(o.status));
@@ -1616,14 +1818,14 @@ function classifyAll(runs, cfg) {
1616
1818
  seenRecently,
1617
1819
  perRun,
1618
1820
  bothFamilies,
1619
- sameShaFlips,
1821
+ confirmed,
1620
1822
  retryRescues,
1621
1823
  directionChanges: dc.changes,
1622
1824
  cfg
1623
1825
  });
1624
1826
  const lastFail = [...collapsed].reverse().find((o) => isFail(o.status));
1625
1827
  const score = bothFamilies ? flakeScore({
1626
- sameShaFlips,
1828
+ confirmed,
1627
1829
  retryRescues,
1628
1830
  directionChanges: dc.changes,
1629
1831
  runsObserved: perRun.length,
@@ -1642,6 +1844,8 @@ function classifyAll(runs, cfg) {
1642
1844
  testId: h.testId,
1643
1845
  suite: h.suite,
1644
1846
  name: h.name,
1847
+ ...h.file === void 0 ? {} : { file: h.file },
1848
+ ...h.reportScope === void 0 ? {} : { reportScope: h.reportScope },
1645
1849
  classification,
1646
1850
  tags,
1647
1851
  flakeScore: score,
@@ -1649,7 +1853,7 @@ function classifyAll(runs, cfg) {
1649
1853
  // over executions (retry attempts included), so a rescued run reads 50%
1650
1854
  passRate: collapsed.length === 0 ? 0 : passes / collapsed.length,
1651
1855
  runsObserved: perRun.length,
1652
- lastStatus: lastObs.status,
1856
+ lastStatus: lastObs.aggregateStatus ?? lastObs.status,
1653
1857
  lastSeen: lastObs.timestamp,
1654
1858
  lastMessage: lastFail?.message,
1655
1859
  medianDurationMs: medianMs,
@@ -1681,14 +1885,43 @@ function classifyAll(runs, cfg) {
1681
1885
  return verdicts;
1682
1886
  }
1683
1887
 
1888
+ // src/parsers/index.ts
1889
+ import { createHash as createHash4 } from "crypto";
1890
+ import path8 from "path";
1891
+
1684
1892
  // src/util/test-id.ts
1685
- import { createHash as createHash2 } from "crypto";
1686
- function makeTestId(suite, name) {
1893
+ import { createHash as createHash3 } from "crypto";
1894
+ import { realpathSync } from "fs";
1895
+ import path7 from "path";
1896
+ function testFileScope(file, cwd) {
1897
+ const normalized = file.replace(/\\/g, "/");
1898
+ const windows = /^(?:[a-z]:\/|\/\/)/i.test(normalized);
1899
+ const paths = windows ? path7.win32 : path7.posix;
1900
+ const root = cwd?.replace(/\\/g, "/");
1901
+ const withinWorkspace = (relative) => relative !== "" && relative !== ".." && !relative.startsWith("../") && !paths.isAbsolute(relative);
1902
+ if (root && windows === /^(?:[a-z]:\/|\/\/)/i.test(root) && paths.isAbsolute(normalized)) {
1903
+ const relative = paths.relative(root, normalized).replace(/\\/g, "/");
1904
+ if (withinWorkspace(relative)) return relative;
1905
+ if (paths === path7) {
1906
+ try {
1907
+ const parent = realpathSync.native(paths.dirname(normalized));
1908
+ const physical = paths.join(parent, paths.basename(normalized));
1909
+ const scoped = paths.relative(realpathSync.native(root), physical).replace(/\\/g, "/");
1910
+ if (withinWorkspace(scoped)) return scoped;
1911
+ } catch {
1912
+ }
1913
+ }
1914
+ }
1915
+ return paths.normalize(normalized).replace(/\\/g, "/");
1916
+ }
1917
+ function makeTestId(suite, name, file) {
1687
1918
  const norm = (s) => s.trim().replace(/\s+/g, " ");
1688
- return createHash2("sha256").update(`${norm(suite)}\0${norm(name)}`).digest("hex").slice(0, 16);
1919
+ const legacy = `${norm(suite)}\0${norm(name)}`;
1920
+ return createHash3("sha256").update(file === void 0 ? legacy : JSON.stringify(["file", file, norm(suite), norm(name)])).digest("hex").slice(0, 16);
1689
1921
  }
1690
1922
 
1691
1923
  // src/parsers/internal.ts
1924
+ import { XMLValidator } from "fast-xml-parser";
1692
1925
  var XML_OPTIONS = {
1693
1926
  ignoreAttributes: false,
1694
1927
  attributeNamePrefix: "@_",
@@ -1696,6 +1929,12 @@ var XML_OPTIONS = {
1696
1929
  parseAttributeValue: false,
1697
1930
  htmlEntities: true
1698
1931
  };
1932
+ function hasClosedXmlRoot(content, rootName, root) {
1933
+ const end = content.trimEnd();
1934
+ const lastTag = end.slice(end.lastIndexOf("<") + 1, -1).trimEnd();
1935
+ if (lastTag === `/${rootName}` && !(isObj(root) && Object.hasOwn(root, rootName))) return true;
1936
+ return XMLValidator.validate(content) === true;
1937
+ }
1699
1938
  function isObj(v) {
1700
1939
  return typeof v === "object" && v !== null && !Array.isArray(v);
1701
1940
  }
@@ -2036,7 +2275,7 @@ var jestParser = {
2036
2275
  if (doc.testResults.length === 0) return true;
2037
2276
  return doc.testResults.some((file) => isObj(file) && Array.isArray(file.assertionResults));
2038
2277
  },
2039
- parse(content, sourcePath) {
2278
+ parse(content, sourcePath, cwd) {
2040
2279
  const results = [];
2041
2280
  const warnings = [];
2042
2281
  const parsed = parseJson(content);
@@ -2055,6 +2294,7 @@ var jestParser = {
2055
2294
  continue;
2056
2295
  }
2057
2296
  const filePath = typeof file.name === "string" && file.name.trim() !== "" ? file.name.replace(/\\/g, "/") : "(unknown file)";
2297
+ const fileScope = filePath === "(unknown file)" ? void 0 : testFileScope(filePath, cwd);
2058
2298
  const assertions = toArray(file.assertionResults);
2059
2299
  let anyAssertionFailed = false;
2060
2300
  for (const assertion of assertions) {
@@ -2074,6 +2314,7 @@ var jestParser = {
2074
2314
  (title) => typeof title === "string" && title.trim() !== ""
2075
2315
  ) : [];
2076
2316
  const suite = ancestors.length > 0 ? ancestors.join(" > ") : filePath;
2317
+ const scope = ancestors.length > 0 ? fileScope : void 0;
2077
2318
  const name = typeof assertion.title === "string" && assertion.title.trim() !== "" ? assertion.title : typeof assertion.fullName === "string" && assertion.fullName.trim() !== "" ? assertion.fullName : status === "error" ? SUITE_PLACEHOLDER : "(unnamed)";
2078
2319
  const durationMs2 = msOf(assertion.duration);
2079
2320
  let message = trimTo(failureMessages[0], 2e3);
@@ -2104,12 +2345,13 @@ var jestParser = {
2104
2345
  ${note}` : note, 2e3);
2105
2346
  }
2106
2347
  const result = {
2107
- testId: makeTestId(suite, name),
2348
+ testId: makeTestId(suite, name, scope),
2108
2349
  suite,
2109
2350
  name,
2110
2351
  status,
2111
2352
  durationMs: durationMs2
2112
2353
  };
2354
+ if (scope !== void 0) result.file = scope;
2113
2355
  if (message !== void 0) result.message = message;
2114
2356
  if (attempts !== void 0) result.attempts = attempts;
2115
2357
  results.push(result);
@@ -2138,6 +2380,16 @@ ${note}` : note, 2e3);
2138
2380
 
2139
2381
  // src/parsers/junit.ts
2140
2382
  import { XMLParser } from "fast-xml-parser";
2383
+
2384
+ // src/util/strict-int.ts
2385
+ function parseStrictInt(value, min, max) {
2386
+ if (!/^-?\d+$/.test(value)) return null;
2387
+ const n = Number.parseInt(value, 10);
2388
+ if (!Number.isSafeInteger(n) || n < min || n > max) return null;
2389
+ return n;
2390
+ }
2391
+
2392
+ // src/parsers/junit.ts
2141
2393
  var xml = new XMLParser(XML_OPTIONS);
2142
2394
  var MESSAGE_MAX_CHARS2 = 2e3;
2143
2395
  var STACK_MAX_CHARS = 1e3;
@@ -2178,7 +2430,7 @@ function detailStack(detail) {
2178
2430
  }
2179
2431
  return void 0;
2180
2432
  }
2181
- function mapTestCase(tc, suiteName, ctx) {
2433
+ function mapTestCase(tc, suiteName, ctx, project, suiteFile) {
2182
2434
  if (!isObj(tc)) return;
2183
2435
  const name = attr(tc, "@_name");
2184
2436
  if (name === void 0) {
@@ -2186,30 +2438,33 @@ function mapTestCase(tc, suiteName, ctx) {
2186
2438
  return;
2187
2439
  }
2188
2440
  const suite = attr(tc, "@_classname") ?? suiteName;
2441
+ const sourceFile = attr(tc, "@_file") ?? suiteFile;
2442
+ const file = sourceFile && sourceFile.replace(/\\/g, "/") !== suite.replace(/\\/g, "/") ? testFileScope(sourceFile, ctx.cwd) : void 0;
2189
2443
  const failures = children(tc, "failure");
2190
2444
  const errors = children(tc, "error");
2191
2445
  const skipped = children(tc, "skipped").length > 0;
2192
2446
  let status = "pass";
2193
2447
  let details = [];
2194
- if (skipped && errors.length === 0) {
2195
- status = "skip";
2448
+ if (skipped) {
2449
+ status = errors.length > 0 ? "error" : "skip";
2450
+ details = errors;
2196
2451
  } else if (failures.length > 0) {
2197
2452
  status = "fail";
2198
2453
  details = failures;
2199
2454
  } else if (errors.length > 0) {
2200
2455
  status = "error";
2201
2456
  details = errors;
2202
- } else if (skipped) {
2203
- status = "skip";
2204
2457
  }
2205
2458
  const detail = details[0];
2206
2459
  const result = {
2207
- testId: makeTestId(suite, name),
2460
+ testId: makeTestId(suite, name, file),
2208
2461
  suite,
2209
2462
  name,
2210
2463
  status,
2211
2464
  durationMs: durationOf(attr(tc, "@_time"))
2212
2465
  };
2466
+ if (file !== void 0) result.file = file;
2467
+ if (project !== void 0) result.playwrightProject = project;
2213
2468
  if (detail !== void 0) {
2214
2469
  let message = detailMessage(detail);
2215
2470
  if (details.length > 1) {
@@ -2251,26 +2506,27 @@ ${note}` : note,
2251
2506
  }
2252
2507
  ctx.results.push(result);
2253
2508
  }
2254
- function collapsePytestReruns(ctx) {
2509
+ function collapsePytestReruns(ctx, excess) {
2255
2510
  const groups = /* @__PURE__ */ new Map();
2256
2511
  for (const r of ctx.results) {
2257
- const g = groups.get(r.testId);
2512
+ const key = JSON.stringify([r.suite, r.name, r.file]);
2513
+ const g = groups.get(key);
2258
2514
  if (g) g.push(r);
2259
- else groups.set(r.testId, [r]);
2515
+ else groups.set(key, [r]);
2260
2516
  }
2261
- const out = [];
2262
- for (const group of groups.values()) {
2517
+ const rerunGroups = [...groups.values()].filter(
2518
+ (group) => group.length > 1 && group.slice(0, -1).every((r) => r.status === "pass" && r.message === void 0 && r.stack === void 0)
2519
+ );
2520
+ const candidates = rerunGroups.reduce((total, group) => total + group.length - 1, 0);
2521
+ if (candidates !== excess) return;
2522
+ const placeholders = /* @__PURE__ */ new Set();
2523
+ for (const group of rerunGroups) {
2263
2524
  const final = group[group.length - 1];
2264
- const earlier = group.slice(0, -1);
2265
- const reruns = earlier.length > 0 && earlier.every((r) => r.status === "pass" && r.message === void 0 && r.stack === void 0);
2266
- if (!reruns) {
2267
- out.push(...group);
2268
- continue;
2269
- }
2525
+ const retries = group.length - 1;
2270
2526
  const how = "pytest-rerunfailures rerun";
2271
2527
  if (final.status === "pass") {
2272
- final.message = flakyRetryMessage(earlier.length, how, void 0, MESSAGE_MAX_CHARS2);
2273
- final.attempts = retryAttempts(earlier.length, "pass");
2528
+ final.message = flakyRetryMessage(retries, how, void 0, MESSAGE_MAX_CHARS2);
2529
+ final.attempts = retryAttempts(retries, "pass");
2274
2530
  ctx.pytestFlaky.push(`${final.suite}.${final.name}`);
2275
2531
  } else if (final.status === "fail" || final.status === "error") {
2276
2532
  const note = `(failed all ${group.length} attempts)`;
@@ -2279,11 +2535,11 @@ function collapsePytestReruns(ctx) {
2279
2535
  ${note}` : note,
2280
2536
  MESSAGE_MAX_CHARS2
2281
2537
  );
2282
- final.attempts = retryAttempts(earlier.length, final.status, final.status);
2538
+ final.attempts = retryAttempts(retries, final.status, final.status);
2283
2539
  }
2284
- out.push(final);
2540
+ for (const earlier of group.slice(0, -1)) placeholders.add(earlier);
2285
2541
  }
2286
- ctx.results = out;
2542
+ ctx.results = ctx.results.filter((result) => !placeholders.has(result));
2287
2543
  }
2288
2544
  function children(el, localName) {
2289
2545
  const out = [];
@@ -2295,18 +2551,45 @@ function children(el, localName) {
2295
2551
  }
2296
2552
  return out;
2297
2553
  }
2298
- function walk(el, inheritedSuite, ctx) {
2554
+ function playwrightSuites(root) {
2555
+ if (!isObj(root) || !Object.hasOwn(root, "@_id") || !Object.hasOwn(root, "@_name")) {
2556
+ return void 0;
2557
+ }
2558
+ const suites = children(root, "testsuite");
2559
+ if (suites.length === 0 || children(root, "testcase").length > 0) return void 0;
2560
+ const projects = /* @__PURE__ */ new Map();
2561
+ let reportTimestamp;
2562
+ for (const suite of suites) {
2563
+ if (!isObj(suite)) return void 0;
2564
+ const name = attr(suite, "@_name");
2565
+ const timestamp = attr(suite, "@_timestamp");
2566
+ const project = suite["@_hostname"];
2567
+ if (!name || !/\.[cm]?[jt]sx?$/i.test(name) || !timestamp || !/^\d{4}-\d\d-\d\dT\d\d:\d\d:\d\d\.\d{3}Z$/.test(timestamp) || reportTimestamp !== void 0 && timestamp !== reportTimestamp || typeof project !== "string" || children(suite, "testsuite").length > 0)
2568
+ return void 0;
2569
+ reportTimestamp = timestamp;
2570
+ for (const testcase of children(suite, "testcase")) {
2571
+ if (!isObj(testcase) || attr(testcase, "@_classname") !== name) return void 0;
2572
+ }
2573
+ projects.set(suite, project);
2574
+ }
2575
+ return projects;
2576
+ }
2577
+ function walk(el, inheritedSuite, ctx, inheritedFile) {
2299
2578
  if (!isObj(el)) return;
2300
- const ownSuite = attr(el, "@_name") ?? inheritedSuite;
2301
- if (ownSuite === "pytest" && !ctx.pytest) {
2302
- const local = { ...ctx, pytest: true, results: [] };
2303
- walk(el, ownSuite, local);
2304
- collapsePytestReruns(local);
2579
+ const suiteName = attr(el, "@_name");
2580
+ const ownSuite = suiteName ?? inheritedSuite;
2581
+ const suiteFile = attr(el, "@_file") ?? inheritedFile;
2582
+ const testCases = children(el, "testcase");
2583
+ const declaredTests = suiteName === "pytest" ? parseStrictInt(attr(el, "@_tests") ?? "", 0, Number.MAX_SAFE_INTEGER) : null;
2584
+ const excess = declaredTests === null ? 0 : testCases.length - declaredTests;
2585
+ const local = excess > 0 ? { ...ctx, results: [] } : ctx;
2586
+ const project = ctx.projects?.get(el);
2587
+ for (const tc of testCases) mapTestCase(tc, ownSuite, local, project, suiteFile);
2588
+ if (local !== ctx) {
2589
+ collapsePytestReruns(local, excess);
2305
2590
  for (const result of local.results) ctx.results.push(result);
2306
- return;
2307
2591
  }
2308
- for (const tc of children(el, "testcase")) mapTestCase(tc, ownSuite, ctx);
2309
- for (const ts of children(el, "testsuite")) walk(ts, ownSuite, ctx);
2592
+ for (const ts of children(el, "testsuite")) walk(ts, ownSuite, ctx, suiteFile);
2310
2593
  }
2311
2594
  var junitParser = {
2312
2595
  name: "junit",
@@ -2314,21 +2597,22 @@ var junitParser = {
2314
2597
  const trimmed = stripBom(content).trimStart();
2315
2598
  return trimmed.startsWith("<") && /<(?:[\w.-]+:)?testsuit/.test(trimmed);
2316
2599
  },
2317
- parse(content, sourcePath) {
2600
+ parse(content, sourcePath, cwd) {
2318
2601
  const ctx = {
2319
2602
  sourcePath,
2603
+ cwd,
2320
2604
  results: [],
2321
2605
  warnings: [],
2322
2606
  flaky: [],
2323
- pytestFlaky: [],
2324
- pytest: false
2607
+ pytestFlaky: []
2325
2608
  };
2326
2609
  const body = stripBom(content);
2327
2610
  if (body.trim() === "") {
2328
2611
  ctx.warnings.push(`junit: ${sourcePath}: file is empty`);
2329
2612
  return { results: ctx.results, warnings: ctx.warnings };
2330
2613
  }
2331
- if (!body.trimEnd().endsWith(">")) {
2614
+ const endsInTag = body.trimEnd().endsWith(">");
2615
+ if (!endsInTag) {
2332
2616
  ctx.warnings.push(`junit: ${sourcePath}: content appears truncated (does not end with '>')`);
2333
2617
  }
2334
2618
  let doc;
@@ -2344,6 +2628,11 @@ var junitParser = {
2344
2628
  }
2345
2629
  const rootKey = Object.keys(doc).find((k) => /(?:^|:)testsuites?$/.test(k));
2346
2630
  let root = rootKey !== void 0 ? doc[rootKey] : void 0;
2631
+ if (endsInTag && rootKey !== void 0 && !hasClosedXmlRoot(body, rootKey, root)) {
2632
+ ctx.warnings.push(
2633
+ `junit: ${sourcePath}: content appears truncated or malformed (check </${rootKey}>)`
2634
+ );
2635
+ }
2347
2636
  if (Array.isArray(root)) {
2348
2637
  ctx.warnings.push(
2349
2638
  `junit: ${sourcePath}: multiple <testsuites> roots found \u2014 using the first`
@@ -2354,6 +2643,7 @@ var junitParser = {
2354
2643
  ctx.warnings.push(`junit: ${sourcePath}: no <testsuites> or <testsuite> root element found`);
2355
2644
  return { results: ctx.results, warnings: ctx.warnings };
2356
2645
  }
2646
+ if (rootKey?.endsWith("testsuites")) ctx.projects = playwrightSuites(root);
2357
2647
  walk(root, "unknown", ctx);
2358
2648
  if (ctx.flaky.length > 0) {
2359
2649
  ctx.warnings.push(flakyRetryWarning("junit", sourcePath, "Surefire rerun", ctx.flaky));
@@ -2363,7 +2653,10 @@ var junitParser = {
2363
2653
  flakyRetryWarning("junit", sourcePath, "pytest-rerunfailures rerun", ctx.pytestFlaky)
2364
2654
  );
2365
2655
  }
2366
- return { results: ctx.results, warnings: ctx.warnings };
2656
+ return {
2657
+ results: ctx.results,
2658
+ warnings: ctx.warnings
2659
+ };
2367
2660
  }
2368
2661
  };
2369
2662
 
@@ -2413,9 +2706,9 @@ function mochawesomeEntries(roots) {
2413
2706
  for (const root of roots) collectFiles(root);
2414
2707
  const onlyFile = files.size === 1 ? [...files][0] : void 0;
2415
2708
  const out = [];
2416
- const walk3 = (suite) => {
2709
+ const walk3 = (suite, inheritedFile) => {
2417
2710
  if (!isObj(suite)) return;
2418
- const file = typeof suite.fullFile === "string" && suite.fullFile !== "" ? suite.fullFile : onlyFile;
2711
+ const file = typeof suite.fullFile === "string" && suite.fullFile !== "" ? suite.fullFile : inheritedFile ?? onlyFile;
2419
2712
  const toEntry = (t) => {
2420
2713
  const err = isObj(t.err) ? { message: t.err.message, stack: t.err.estack } : t.err;
2421
2714
  return { ...t, file, err };
@@ -2432,7 +2725,7 @@ function mochawesomeEntries(roots) {
2432
2725
  for (const h of hooks) {
2433
2726
  if (isObj(h) && h.state === "failed") out.push([toEntry(h), "fail"]);
2434
2727
  }
2435
- for (const child2 of Array.isArray(suite.suites) ? suite.suites : []) walk3(child2);
2728
+ for (const child2 of Array.isArray(suite.suites) ? suite.suites : []) walk3(child2, file);
2436
2729
  };
2437
2730
  for (const root of roots) walk3(root);
2438
2731
  return out;
@@ -2465,7 +2758,7 @@ var mochaParser = {
2465
2758
  if (hasTestList && doc.stats !== void 0) return true;
2466
2759
  return Array.isArray(doc.passes) && Array.isArray(doc.failures);
2467
2760
  },
2468
- parse(content, sourcePath) {
2761
+ parse(content, sourcePath, cwd) {
2469
2762
  const results = [];
2470
2763
  const warnings = [];
2471
2764
  const parsed = parseJson(content);
@@ -2540,17 +2833,20 @@ var mochaParser = {
2540
2833
  const title = typeof entry.title === "string" && entry.title.trim() !== "" ? entry.title.trim() : fullTitle !== "" ? fullTitle : "(unnamed)";
2541
2834
  const finalStatus = statuses[n] ?? "pass";
2542
2835
  const suite = deriveSuite(entry, title, fullTitle);
2836
+ const file = typeof entry.file === "string" ? entry.file.trim().replace(/\\/g, "/") : "";
2837
+ const scope = file && file !== suite ? testFileScope(file, cwd) : void 0;
2543
2838
  const isHook = HOOK_TITLE.test(title);
2544
2839
  const name = isHook ? hookName(title) : title;
2545
2840
  if (isHook && finalStatus === "fail") hooks.push(`${suite} ${name}`);
2546
2841
  const durationMs2 = msOf(entry.duration);
2547
2842
  const result = {
2548
- testId: makeTestId(suite, name),
2843
+ testId: makeTestId(suite, name, scope),
2549
2844
  suite,
2550
2845
  name,
2551
2846
  status: finalStatus,
2552
2847
  durationMs: durationMs2
2553
2848
  };
2849
+ if (scope !== void 0) result.file = scope;
2554
2850
  const err = entry.err;
2555
2851
  if (typeof err === "string") {
2556
2852
  const message = trimTo(err, 2e3);
@@ -2615,6 +2911,18 @@ function textOf2(value, max) {
2615
2911
  function isFailFamily2(status) {
2616
2912
  return status === "fail" || status === "error";
2617
2913
  }
2914
+ var OUTCOME_STATUS = {
2915
+ expected: "pass",
2916
+ unexpected: "fail",
2917
+ flaky: "pass",
2918
+ skipped: "skip"
2919
+ };
2920
+ function reporterOutcome(value) {
2921
+ if (typeof value === "string" && Object.hasOwn(OUTCOME_STATUS, value)) {
2922
+ return value;
2923
+ }
2924
+ return void 0;
2925
+ }
2618
2926
  function severity(row) {
2619
2927
  if (isFailFamily2(row.status)) return 0;
2620
2928
  if (row.status === "pass" && row.attempts.some((a) => isFailFamily2(a.status))) return 1;
@@ -2625,6 +2933,8 @@ function projectRow(project, tests) {
2625
2933
  const attempts = [];
2626
2934
  let failedFinal = false;
2627
2935
  let lastFinal = "skip";
2936
+ let preservesOrder = false;
2937
+ let reportedFlaky = false;
2628
2938
  let skipReason2;
2629
2939
  for (const test of tests) {
2630
2940
  const own = [];
@@ -2637,9 +2947,15 @@ function projectRow(project, tests) {
2637
2947
  if (error !== void 0) attempt.error = error;
2638
2948
  own.push(attempt);
2639
2949
  }
2640
- const final = own[own.length - 1]?.status ?? "skip";
2950
+ const lastAttempt = own[own.length - 1]?.status ?? "skip";
2951
+ const outcome = reporterOutcome(test.status);
2952
+ const final = outcome === void 0 ? lastAttempt : OUTCOME_STATUS[outcome];
2953
+ if (outcome !== void 0 && final !== lastAttempt) {
2954
+ preservesOrder = true;
2955
+ reportedFlaky ||= outcome === "flaky";
2956
+ }
2641
2957
  if (isFailFamily2(final)) failedFinal = true;
2642
- lastFinal = final;
2958
+ if (final !== "skip") lastFinal = final;
2643
2959
  if (final === "skip" && skipReason2 === void 0 && Array.isArray(test.annotations)) {
2644
2960
  const note = test.annotations.find((a) => isObj(a) && a.type === "skip");
2645
2961
  if (isObj(note)) skipReason2 = textOf2(note.description, MESSAGE_MAX_CHARS3);
@@ -2647,12 +2963,15 @@ function projectRow(project, tests) {
2647
2963
  attempts.push(...own);
2648
2964
  }
2649
2965
  const status = failedFinal ? "fail" : lastFinal;
2650
- if (attempts.length > 0 && attempts[attempts.length - 1].status !== status) {
2651
- const fails = attempts.filter((a) => a.status === status);
2966
+ if (!preservesOrder && attempts.length > 0 && attempts[attempts.length - 1].status !== status) {
2967
+ const matching = attempts.filter((a) => a.status === status);
2652
2968
  const rest = attempts.filter((a) => a.status !== status);
2653
- attempts.splice(0, attempts.length, ...rest, ...fails);
2969
+ attempts.splice(0, attempts.length, ...rest, ...matching);
2654
2970
  }
2655
2971
  const row = { project, status, attempts };
2972
+ if (preservesOrder) {
2973
+ row.reportedOutcome = status === "pass" ? reportedFlaky ? "flaky" : "expected" : status === "skip" ? "skipped" : "unexpected";
2974
+ }
2656
2975
  if (skipReason2 !== void 0) row.skipReason = skipReason2;
2657
2976
  return row;
2658
2977
  }
@@ -2679,19 +2998,24 @@ function mapSpec(spec, file, titles, ctx) {
2679
2998
  suite: file,
2680
2999
  name,
2681
3000
  status: row.status,
2682
- durationMs: row.attempts[row.attempts.length - 1]?.durationMs ?? null
3001
+ durationMs: row.attempts.filter((attempt) => attempt.status === row.status).at(-1)?.durationMs ?? null
2683
3002
  };
3003
+ if (row.reportedOutcome !== void 0) result.reportedOutcome = row.reportedOutcome;
2684
3004
  const failures = row.attempts.filter((a) => isFailFamily2(a.status));
2685
3005
  const firstError = failures.find((a) => a.error !== void 0)?.error;
2686
3006
  let message;
2687
3007
  if (row.status === "pass" && failures.length > 0) {
2688
- message = flakyRetryMessage(
3008
+ message = row.reportedOutcome === "flaky" ? [
3009
+ "flaky: Playwright reported mixed outcomes during retries",
3010
+ textOf2(firstError?.message, MESSAGE_MAX_CHARS3)
3011
+ ].filter(Boolean).join(": ") : flakyRetryMessage(
2689
3012
  failures.length,
2690
3013
  "Playwright retry",
2691
3014
  textOf2(firstError?.message, MESSAGE_MAX_CHARS3),
2692
3015
  MESSAGE_MAX_CHARS3
2693
3016
  );
2694
- ctx.flaky.push(`${file} > ${name}`);
3017
+ if (row.reportedOutcome === "flaky") ctx.aggregateFlakes++;
3018
+ else ctx.flaky.push(`${file} > ${name}`);
2695
3019
  } else if (isFailFamily2(row.status)) {
2696
3020
  const error = [...failures].reverse().find((a) => a.error !== void 0)?.error;
2697
3021
  message = textOf2(error?.message, MESSAGE_MAX_CHARS3) ?? textOf2(error?.value, MESSAGE_MAX_CHARS3);
@@ -2709,7 +3033,9 @@ ${note}` : note, MESSAGE_MAX_CHARS3);
2709
3033
  message = trimTo(`[${row.project}] ${message}`, MESSAGE_MAX_CHARS3);
2710
3034
  }
2711
3035
  if (message !== void 0) result.message = message;
2712
- if (row.attempts.length > 1) result.attempts = row.attempts.map((a) => a.status);
3036
+ if (row.attempts.length > 1 || row.reportedOutcome && row.attempts.length === 1) {
3037
+ result.attempts = row.attempts.map((a) => a.status);
3038
+ }
2713
3039
  ctx.results.push(result);
2714
3040
  }
2715
3041
  function walk2(suite, file, titles, ctx) {
@@ -2731,7 +3057,7 @@ var playwrightParser = {
2731
3057
  return isObj(doc) && Array.isArray(doc.suites) && isObj(doc.config);
2732
3058
  },
2733
3059
  parse(content, sourcePath) {
2734
- const ctx = { sourcePath, results: [], warnings: [], flaky: [] };
3060
+ const ctx = { sourcePath, results: [], warnings: [], flaky: [], aggregateFlakes: 0 };
2735
3061
  const parsed = parseJson(content);
2736
3062
  if (!("doc" in parsed)) {
2737
3063
  return {
@@ -2772,6 +3098,11 @@ var playwrightParser = {
2772
3098
  if (ctx.flaky.length > 0) {
2773
3099
  ctx.warnings.push(flakyRetryWarning("playwright", sourcePath, "Playwright retry", ctx.flaky));
2774
3100
  }
3101
+ if (ctx.aggregateFlakes > 0) {
3102
+ ctx.warnings.push(
3103
+ `playwright: ${sourcePath}: ${ctx.aggregateFlakes} test(s) FLAKY according to Playwright's aggregate verdict`
3104
+ );
3105
+ }
2775
3106
  return { results: ctx.results, warnings: ctx.warnings };
2776
3107
  }
2777
3108
  };
@@ -2791,9 +3122,9 @@ var OUTCOMES = {
2791
3122
  };
2792
3123
  function junitAddress(nodeid) {
2793
3124
  const bracket = nodeid.indexOf("[");
2794
- const path9 = bracket === -1 ? nodeid : nodeid.slice(0, bracket);
3125
+ const path12 = bracket === -1 ? nodeid : nodeid.slice(0, bracket);
2795
3126
  const params = bracket === -1 ? "" : nodeid.slice(bracket);
2796
- const names = path9.split("::");
3127
+ const names = path12.split("::");
2797
3128
  names[0] = names[0].replace(/\//g, ".").replace(/\.py$/, "");
2798
3129
  names[names.length - 1] += params;
2799
3130
  return { classname: names.slice(0, -1).join("."), name: names[names.length - 1] };
@@ -3222,8 +3553,9 @@ var trxParser = {
3222
3553
  ctx.warnings.push(`trx: ${sourcePath}: file is empty`);
3223
3554
  return { results: ctx.results, warnings: ctx.warnings };
3224
3555
  }
3225
- if (!/<\/(?:[\w.-]+:)?TestRun>\s*$/.test(body)) {
3226
- ctx.warnings.push(`trx: ${sourcePath}: content appears truncated (no closing </TestRun>)`);
3556
+ const endsInTag = body.trimEnd().endsWith(">");
3557
+ if (!endsInTag) {
3558
+ ctx.warnings.push(`trx: ${sourcePath}: content appears truncated (does not end with '>')`);
3227
3559
  }
3228
3560
  let doc;
3229
3561
  try {
@@ -3242,6 +3574,11 @@ var trxParser = {
3242
3574
  return { results: ctx.results, warnings: ctx.warnings };
3243
3575
  }
3244
3576
  let root = doc[rootKey];
3577
+ if (endsInTag && !hasClosedXmlRoot(body, rootKey, root)) {
3578
+ ctx.warnings.push(
3579
+ `trx: ${sourcePath}: content appears truncated or malformed (check </${rootKey}>)`
3580
+ );
3581
+ }
3245
3582
  if (Array.isArray(root)) {
3246
3583
  ctx.warnings.push(`trx: ${sourcePath}: multiple <TestRun> roots found \u2014 using the first`);
3247
3584
  root = root[0];
@@ -3283,7 +3620,7 @@ function bomTolerant(parser) {
3283
3620
  return {
3284
3621
  name: parser.name,
3285
3622
  sniff: (content) => parser.sniff(stripBom(content)),
3286
- parse: (content, sourcePath) => parser.parse(stripBom(content), sourcePath)
3623
+ parse: (content, sourcePath, cwd) => parser.parse(stripBom(content), sourcePath, cwd)
3287
3624
  };
3288
3625
  }
3289
3626
  var parsers = [
@@ -3305,6 +3642,54 @@ function detectParser(content) {
3305
3642
  }
3306
3643
  return null;
3307
3644
  }
3645
+ function reportScope(file, cwd, scopes) {
3646
+ const relative = path8.relative(cwd, file);
3647
+ const matching = new Set(
3648
+ Object.entries(scopes).filter(([glob]) => matchesReportGlob(relative, glob)).map(([, scope]) => scope)
3649
+ );
3650
+ if (matching.size > 1)
3651
+ throw new Error(`reportScopes overlap for ${file}; use one scope per report`);
3652
+ return [...matching][0];
3653
+ }
3654
+ function validateReportScopes(files, cwd, scopes) {
3655
+ if (!scopes) return;
3656
+ for (const file of files) reportScope(file, cwd, scopes);
3657
+ }
3658
+ function parseReport(parser, content, file, cwd, scopes = {}) {
3659
+ const scope = reportScope(file, cwd, scopes);
3660
+ const parsed = parser.parse(content, file, cwd);
3661
+ if (scope !== void 0) {
3662
+ for (const result of parsed.results) {
3663
+ result.reportScope = scope;
3664
+ result.testId = createHash4("sha256").update(JSON.stringify(["report-scope", scope, result.testId])).digest("hex").slice(0, 16);
3665
+ }
3666
+ }
3667
+ if (!["junit", "jest", "mocha"].includes(parser.name)) return parsed;
3668
+ const missingFile = /* @__PURE__ */ new Map();
3669
+ for (const result of parsed.results) {
3670
+ if (result.file !== void 0 || result.playwrightProject !== void 0) continue;
3671
+ const duplicates = missingFile.get(result.testId);
3672
+ if (duplicates) duplicates.push(result);
3673
+ else missingFile.set(result.testId, [result]);
3674
+ }
3675
+ const redundant = /* @__PURE__ */ new Set();
3676
+ let ambiguous = 0;
3677
+ for (const rows of missingFile.values()) {
3678
+ const winner = rows.reduce(
3679
+ (best, row) => statusSeverity[row.status] > statusSeverity[best.status] ? row : best
3680
+ );
3681
+ if (!rows.some((row) => row.status !== winner.status)) continue;
3682
+ ambiguous++;
3683
+ for (const row of rows) if (row !== winner) redundant.add(row);
3684
+ }
3685
+ if (ambiguous > 0) {
3686
+ parsed.results = parsed.results.filter((row) => !redundant.has(row));
3687
+ parsed.warnings.push(
3688
+ `${file}: ${ambiguous} test identit${ambiguous === 1 ? "y has" : "ies have"} conflicting rows without file information. Kept the strongest result. Include test file paths or split the tests into separately scoped reports.`
3689
+ );
3690
+ }
3691
+ return parsed;
3692
+ }
3308
3693
  function unrecognizedReason(content) {
3309
3694
  const body = stripBom(content);
3310
3695
  if (body.trim() === "") return "empty report file";
@@ -3717,9 +4102,12 @@ function redactData(data) {
3717
4102
  verdicts: data.verdicts.map((v) => {
3718
4103
  const name = escapeControlChars(redact(v.name));
3719
4104
  const suite = escapeControlChars(redact(v.suite));
4105
+ const file = v.file === void 0 ? void 0 : escapeControlChars(redact(v.file));
4106
+ const reportScope2 = v.reportScope === void 0 ? void 0 : escapeControlChars(redact(v.reportScope));
3720
4107
  const lastMessage = v.lastMessage ? escapeControlCharsMultiline(redact(v.lastMessage)) : v.lastMessage;
3721
- if (name === v.name && suite === v.suite && lastMessage === v.lastMessage) return v;
3722
- return { ...v, name, suite, lastMessage };
4108
+ if (name === v.name && suite === v.suite && file === v.file && reportScope2 === v.reportScope && lastMessage === v.lastMessage)
4109
+ return v;
4110
+ return { ...v, name, suite, file, reportScope: reportScope2, lastMessage };
3723
4111
  }),
3724
4112
  runs: data.runs.map(
3725
4113
  (r) => r.commitSha === void 0 ? r : { ...r, commitSha: escapeControlChars(r.commitSha) }
@@ -4699,7 +5087,8 @@ ${lightTokens} }
4699
5087
 
4700
5088
  td = el('td', 'td-name');
4701
5089
  var nameDiv = el('div', 'tname');
4702
- nameDiv.title = v.suite + ' :: ' + v.name;
5090
+ nameDiv.title = v.suite + ' :: ' + v.name + (v.file ? ' (' + v.file + ')' : '') +
5091
+ (v.reportScope ? ' [' + v.reportScope + ']' : '');
4703
5092
  nameDiv.appendChild(el('span', 'suite', midTrunc(v.suite, 46) + ' ::'));
4704
5093
  nameDiv.appendChild(el('span', 'nm', midTrunc(v.name, 56)));
4705
5094
  td.appendChild(nameDiv);
@@ -5119,7 +5508,7 @@ ${hasVerdicts ? drawerMarkup : ""}
5119
5508
  }
5120
5509
 
5121
5510
  // src/types.ts
5122
- var FLAKEFINDER_VERSION = "1.2.0";
5511
+ var FLAKEFINDER_VERSION = "1.2.1";
5123
5512
 
5124
5513
  // src/report/json.ts
5125
5514
  var JSON_SCHEMA_VERSION = 1;
@@ -5132,9 +5521,12 @@ function renderJson(verdicts, cfg) {
5132
5521
  verdicts: verdicts.map((v) => {
5133
5522
  const name = redact(v.name);
5134
5523
  const suite = redact(v.suite);
5524
+ const file = v.file === void 0 ? void 0 : redact(v.file);
5525
+ const reportScope2 = v.reportScope === void 0 ? void 0 : redact(v.reportScope);
5135
5526
  const lastMessage = v.lastMessage ? redact(v.lastMessage) : v.lastMessage;
5136
- if (name === v.name && suite === v.suite && lastMessage === v.lastMessage) return v;
5137
- return { ...v, name, suite, lastMessage };
5527
+ if (name === v.name && suite === v.suite && file === v.file && reportScope2 === v.reportScope && lastMessage === v.lastMessage)
5528
+ return v;
5529
+ return { ...v, name, suite, file, reportScope: reportScope2, lastMessage };
5138
5530
  })
5139
5531
  };
5140
5532
  return JSON.stringify(payload, null, 2);
@@ -5177,7 +5569,7 @@ function truncateMiddle(s, max) {
5177
5569
  function renderTerminal(allVerdicts, opts) {
5178
5570
  const color = makeColor(opts.color);
5179
5571
  const bold = (s) => color("1", s);
5180
- const dim2 = (s) => color("2", s);
5572
+ const dim = (s) => color("2", s);
5181
5573
  const lines = [];
5182
5574
  const beforeFilter = allVerdicts.length;
5183
5575
  const verdicts = opts.threshold == null ? allVerdicts : allVerdicts.filter(
@@ -5213,7 +5605,7 @@ function renderTerminal(allVerdicts, opts) {
5213
5605
  );
5214
5606
  if (hiddenBelowThreshold > 0) {
5215
5607
  lines.push(
5216
- dim2(
5608
+ dim(
5217
5609
  `${hiddenBelowThreshold} flaky-suspected test(s) hidden below score ${opts.threshold} \u2014 show them with --all or a lower --threshold`
5218
5610
  ),
5219
5611
  ""
@@ -5230,9 +5622,9 @@ function renderTerminal(allVerdicts, opts) {
5230
5622
  const runs = String(v.runsObserved).padStart(3);
5231
5623
  const pass = `${Math.round(v.passRate * 100)}%`.padStart(4);
5232
5624
  const med = fmtMs(v.medianDurationMs).padStart(6);
5233
- const tags = v.tags.length > 0 ? dim2(` [${safe(v.tags.join(", "))}]`) : "";
5625
+ const tags = v.tags.length > 0 ? dim(` [${safe(v.tags.join(", "))}]`) : "";
5234
5626
  lines.push(
5235
- ` ${color(meta.colorCode, score)} conf ${conf} runs ${runs} pass ${pass} med ${med} ${safe(v.suite)} ${dim2("::")} ${bold(truncateMiddle(safe(v.name), 48))}${tags}`
5627
+ ` ${color(meta.colorCode, score)} conf ${conf} runs ${runs} pass ${pass} med ${med} ${safe(v.suite)} ${dim("::")} ${bold(truncateMiddle(safe(v.name), 48))}${tags}`
5236
5628
  );
5237
5629
  }
5238
5630
  lines.push("");
@@ -5242,16 +5634,16 @@ function renderTerminal(allVerdicts, opts) {
5242
5634
  const list = byClass.get(cls);
5243
5635
  if (!list || list.length === 0) continue;
5244
5636
  const meta = CLASS_META[cls];
5245
- lines.push(dim2(`${meta.label} \u2014 ${list.length}`));
5637
+ lines.push(dim(`${meta.label} \u2014 ${list.length}`));
5246
5638
  const shown = cls === "passing" ? list.slice(0, 20) : list;
5247
5639
  for (const v of shown) {
5248
5640
  const med = fmtMs(v.medianDurationMs).padStart(6);
5249
- const tags = v.tags.length > 0 ? dim2(` [${safe(v.tags.join(", "))}]`) : "";
5641
+ const tags = v.tags.length > 0 ? dim(` [${safe(v.tags.join(", "))}]`) : "";
5250
5642
  lines.push(
5251
- ` ${dim2(String(v.flakeScore).padStart(3))} runs ${String(v.runsObserved).padStart(3)} med ${med} ${safe(v.suite)} ${dim2("::")} ${truncateMiddle(safe(v.name), 48)}${tags}`
5643
+ ` ${dim(String(v.flakeScore).padStart(3))} runs ${String(v.runsObserved).padStart(3)} med ${med} ${safe(v.suite)} ${dim("::")} ${truncateMiddle(safe(v.name), 48)}${tags}`
5252
5644
  );
5253
5645
  }
5254
- if (cls === "passing" && list.length > 20) lines.push(dim2(` \u2026and ${list.length - 20} more`));
5646
+ if (cls === "passing" && list.length > 20) lines.push(dim(` \u2026and ${list.length - 20} more`));
5255
5647
  lines.push("");
5256
5648
  }
5257
5649
  }
@@ -5260,7 +5652,7 @@ function renderTerminal(allVerdicts, opts) {
5260
5652
  const skipped = byClass.get("skipped")?.length ?? 0;
5261
5653
  const gone = byClass.get("gone")?.length ?? 0;
5262
5654
  lines.push(
5263
- dim2(`ok: ${passing} passing \xB7 ${skipped} skipped \xB7 ${gone} gone from recent runs`),
5655
+ dim(`ok: ${passing} passing \xB7 ${skipped} skipped \xB7 ${gone} gone from recent runs`),
5264
5656
  ""
5265
5657
  );
5266
5658
  }
@@ -5269,23 +5661,31 @@ function renderTerminal(allVerdicts, opts) {
5269
5661
  const worst = [...byClass.entries()].flatMap(([c, vs]) => PROBLEM_CLASSES.slice(0, 3).includes(c) ? vs : []).sort((a, b) => b.flakeScore - a.flakeScore)[0];
5270
5662
  lines.push("next steps:");
5271
5663
  if (worst) {
5272
- lines.push(` ${dim2("\u2022")} quarantine the worst offender:`);
5664
+ lines.push(` ${dim("\u2022")} quarantine the worst offender:`);
5273
5665
  lines.push(` ${color("36", `flakefinder quarantine add ${safe(worst.testId)}`)}`);
5274
5666
  }
5275
- lines.push(` ${dim2("\u2022")} full interactive report: ${color("36", "flakefinder html")}`);
5667
+ lines.push(` ${dim("\u2022")} full interactive report: ${color("36", "flakefinder html")}`);
5276
5668
  }
5277
5669
  return lines.join("\n");
5278
5670
  }
5279
5671
 
5280
5672
  // src/runner/wrap.ts
5281
5673
  import { spawn, spawnSync as spawnSync3 } from "child_process";
5282
- import { createHash as createHash4, randomUUID } from "crypto";
5283
- import { existsSync as existsSync5, mkdtempSync, readFileSync as readFileSync6, rmSync as rmSync3, statSync as statSync6, writeFileSync as writeFileSync3 } from "fs";
5674
+ import { createHash as createHash6, randomUUID } from "crypto";
5675
+ import {
5676
+ existsSync as existsSync6,
5677
+ mkdtempSync,
5678
+ readFileSync as readFileSync7,
5679
+ rmdirSync,
5680
+ rmSync as rmSync3,
5681
+ statSync as statSync6,
5682
+ writeFileSync as writeFileSync4
5683
+ } from "fs";
5284
5684
  import { tmpdir } from "os";
5285
- import path7 from "path";
5685
+ import path10 from "path";
5286
5686
 
5287
5687
  // src/util/read-text.ts
5288
- import { readFileSync as readFileSync4 } from "fs";
5688
+ import { readFileSync as readFileSync5 } from "fs";
5289
5689
  import { gunzipSync } from "zlib";
5290
5690
  function decodeText(buf) {
5291
5691
  if (buf.length >= 2 && buf[0] === 31 && buf[1] === 139) {
@@ -5323,14 +5723,14 @@ function swap16(buf) {
5323
5723
  return out;
5324
5724
  }
5325
5725
  function readTextFile(file) {
5326
- return decodeText(readFileSync4(file));
5726
+ return decodeText(readFileSync5(file));
5327
5727
  }
5328
5728
 
5329
5729
  // src/runner/git-state.ts
5330
5730
  import { spawnSync as spawnSync2 } from "child_process";
5331
- import { createHash as createHash3 } from "crypto";
5332
- import { readFileSync as readFileSync5, realpathSync, statSync as statSync5 } from "fs";
5333
- import path6 from "path";
5731
+ import { createHash as createHash5 } from "crypto";
5732
+ import { readFileSync as readFileSync6, realpathSync as realpathSync2, statSync as statSync5 } from "fs";
5733
+ import path9 from "path";
5334
5734
  var MAX_HASHED_BYTES = 8 * 1024 * 1024;
5335
5735
  var GIT_TIMEOUT_MS = 15e3;
5336
5736
  function git(cwd, args) {
@@ -5344,10 +5744,10 @@ function git(cwd, args) {
5344
5744
  }
5345
5745
  function real(p) {
5346
5746
  try {
5347
- return realpathSync.native(p);
5747
+ return realpathSync2.native(p);
5348
5748
  } catch {
5349
- const parent = path6.dirname(p);
5350
- return parent === p ? p : path6.join(real(parent), path6.basename(p));
5749
+ const parent = path9.dirname(p);
5750
+ return parent === p ? p : path9.join(real(parent), path9.basename(p));
5351
5751
  }
5352
5752
  }
5353
5753
  function parsePorcelainZ(out) {
@@ -5369,19 +5769,19 @@ function detectCodeState(cwd, exclude = []) {
5369
5769
  const top = git(cwd, ["rev-parse", "--show-toplevel"])?.trim();
5370
5770
  if (status === null || !top) return { commitSha: head, dirtyFiles: [] };
5371
5771
  const root = real(top);
5372
- const excluded = exclude.map((p) => real(path6.resolve(cwd, p)));
5373
- const isExcluded = (abs) => excluded.some((e) => abs === e || abs.startsWith(e + path6.sep));
5374
- const dirtyFiles = parsePorcelainZ(status).filter((rel) => !isExcluded(path6.join(root, rel))).sort();
5772
+ const excluded = exclude.map((p) => real(path9.resolve(cwd, p)));
5773
+ const isExcluded = (abs) => excluded.some((e) => abs === e || abs.startsWith(e + path9.sep));
5774
+ const dirtyFiles = parsePorcelainZ(status).filter((rel) => !isExcluded(path9.join(root, rel))).sort();
5375
5775
  if (dirtyFiles.length === 0) return { commitSha: head, dirtyFiles };
5376
- const h = createHash3("sha256");
5776
+ const h = createHash5("sha256");
5377
5777
  for (const rel of dirtyFiles) {
5378
- const abs = path6.join(root, rel);
5778
+ const abs = path9.join(root, rel);
5379
5779
  h.update(rel).update("\0");
5380
5780
  try {
5381
5781
  const st = statSync5(abs);
5382
5782
  if (!st.isFile()) h.update(`[${st.isDirectory() ? "dir" : "other"}]`);
5383
5783
  else if (st.size > MAX_HASHED_BYTES) h.update(`[${st.size}:${st.mtimeMs}]`);
5384
- else h.update(readFileSync5(abs));
5784
+ else h.update(readFileSync6(abs));
5385
5785
  } catch {
5386
5786
  h.update("[deleted]");
5387
5787
  }
@@ -5401,7 +5801,7 @@ function statOf(file) {
5401
5801
  }
5402
5802
  function shaOf(file) {
5403
5803
  try {
5404
- return createHash4("sha256").update(readFileSync6(file)).digest("hex");
5804
+ return createHash6("sha256").update(readFileSync7(file)).digest("hex");
5405
5805
  } catch {
5406
5806
  return null;
5407
5807
  }
@@ -5476,10 +5876,10 @@ function commandResolvable(word, cwd, env = process.env, platform = process.plat
5476
5876
  return false;
5477
5877
  }
5478
5878
  };
5479
- if (/[\\/]/.test(word)) return exts.some((e) => isFile(path7.resolve(cwd, word + e)));
5879
+ if (/[\\/]/.test(word)) return exts.some((e) => isFile(path10.resolve(cwd, word + e)));
5480
5880
  const dirs = (env.PATH ?? env.Path ?? "").split(platform === "win32" ? ";" : ":");
5481
5881
  if (platform === "win32") dirs.unshift(cwd);
5482
- return dirs.some((d) => d !== "" && exts.some((e) => isFile(path7.join(d, word + e))));
5882
+ return dirs.some((d) => d !== "" && exts.some((e) => isFile(path10.join(d, word + e))));
5483
5883
  }
5484
5884
  function missingCommandWord(command, cwd) {
5485
5885
  for (const seg of shellSegments(command)) {
@@ -5643,7 +6043,7 @@ function spawnCommand(command, cwd, timeoutSeconds, currentChild, env = process.
5643
6043
  });
5644
6044
  child2.on("close", (code) => {
5645
6045
  if (abandoned) return;
5646
- const missing = useShell2 && code !== null && SHELL_NOT_FOUND_CODES.includes(code) && !timedOut ? missingCommandWord(command, cwd) ?? // code 1 is also cmd.exe's ordinary failure code; only the
6046
+ const missing = useShell2 && code !== null && SHELL_NOT_FOUND_CODES.includes(code) && !timedOut && (code !== 1 || shellSegments(command).length === 1) ? missingCommandWord(command, cwd) ?? // code 1 is also cmd.exe's ordinary failure code; only the
5647
6047
  // definitive 9009 may stand in for a command word we cannot
5648
6048
  // judge statically (a `$VAR` that expanded to nothing)
5649
6049
  (directNotFound && (process.platform !== "win32" || code === 9009) ? command[shellSegments(command)[0]?.cmd ?? 0] : void 0) : void 0;
@@ -5663,7 +6063,7 @@ function spawnCommand(command, cwd, timeoutSeconds, currentChild, env = process.
5663
6063
  });
5664
6064
  }
5665
6065
  async function runLive(command, cfg, opts) {
5666
- const cwd = path7.resolve(opts.cwd);
6066
+ const cwd = path10.resolve(opts.cwd);
5667
6067
  const runId = randomUUID();
5668
6068
  const { commitSha, dirtyFiles } = detectCodeState(cwd, [
5669
6069
  cfg.storeDir,
@@ -5682,10 +6082,22 @@ async function runLive(command, cfg, opts) {
5682
6082
  let quarantinedIds = /* @__PURE__ */ new Set();
5683
6083
  let exactDeselect = null;
5684
6084
  if (opts.applyQuarantine) {
5685
- const entries = loadQuarantine(path7.resolve(cwd, cfg.quarantineFile));
6085
+ const entries = loadQuarantine(path10.resolve(cwd, cfg.quarantineFile));
5686
6086
  quarantinedIds = new Set(entries.map((e) => e.testId));
5687
6087
  if (runner === "pytest" || runner === "jest" || runner === "mocha") {
5688
6088
  if (entries.length > 0) {
6089
+ if (runner !== "pytest") {
6090
+ const runs = new HistoryStore(path10.resolve(cwd, cfg.storeDir)).runs();
6091
+ const ambiguous = ambiguousQuarantineName(
6092
+ entries.map((e) => e.name),
6093
+ runs
6094
+ );
6095
+ if (ambiguous !== void 0) {
6096
+ throw new Error(
6097
+ `quarantine cannot exclude ${JSON.stringify(ambiguous)} in only one file or report scope with ${runner}; remove the entry or run with --no-quarantine`
6098
+ );
6099
+ }
6100
+ }
5689
6101
  quarantineFlags = exclusionArgs(runner, entries, cwd);
5690
6102
  if (runner === "pytest") exactDeselect = setUpExactDeselect(quarantineFlags);
5691
6103
  quarantinedNames = entries.map((e) => e.name);
@@ -5715,6 +6127,7 @@ async function runLive(command, cfg, opts) {
5715
6127
  let interrupted = false;
5716
6128
  let warnedSelectorClash = false;
5717
6129
  let notedSelectorMerge = false;
6130
+ let mochaFilterFile;
5718
6131
  const onInterrupt = (signal) => {
5719
6132
  interrupted = true;
5720
6133
  if (currentChild.ref) interruptTree(currentChild.ref, signal);
@@ -5727,7 +6140,9 @@ async function runLive(command, cfg, opts) {
5727
6140
  let note = "";
5728
6141
  if (attempt > 1 && cfg.retryMode !== "full") {
5729
6142
  const previous = attempts.filter((r) => r.attempt === attempt - 1);
5730
- const failed = failedNamesOf(previous).filter((n) => !quarantinedNames.includes(n));
6143
+ const failed = failedNamesOf(reconcileReportResults(previous)).filter(
6144
+ (n) => !quarantinedNames.includes(n)
6145
+ );
5731
6146
  let targeted = failedOnlyArgs(runner, failed, quarantinedNames);
5732
6147
  if (runner === "pytest" && targeted) {
5733
6148
  if (pytestCacheDisabled(command, cwd)) targeted = null;
@@ -5752,6 +6167,25 @@ async function runLive(command, cfg, opts) {
5752
6167
  note = "full re-run (no targeted adapter)";
5753
6168
  }
5754
6169
  }
6170
+ if (runner === "mocha" && extraArgs[0] === "--grep" && extraArgs[1] !== void 0) {
6171
+ mochaFilterFile ??= path10.join(mkdtempSync(path10.join(tmpdir(), "ff-mocha-")), "filter.cjs");
6172
+ writeFileSync4(
6173
+ mochaFilterFile,
6174
+ `const allowed = new RegExp(${JSON.stringify(extraArgs[1])});
6175
+ const { createRequire } = require("node:module");
6176
+ const { resolve } = require("node:path");
6177
+ const { Runner } = createRequire(resolve(process.argv[1] || "mocha.cjs"))("mocha");
6178
+ const grep = Runner.prototype.grep;
6179
+ Runner.prototype.grep = function (pattern, invert) {
6180
+ const combined = /(?:)/;
6181
+ combined.test = title => Boolean(pattern.test(title)) !== Boolean(invert) && allowed.test(title);
6182
+ return grep.call(this, combined, false);
6183
+ };
6184
+ `,
6185
+ "utf8"
6186
+ );
6187
+ extraArgs = ["--require", mochaFilterFile];
6188
+ }
5755
6189
  const merged = mergeUserSelector(command, extraArgs);
5756
6190
  if (merged.userPatterns.length > 0 && !notedSelectorMerge) {
5757
6191
  notedSelectorMerge = true;
@@ -5768,11 +6202,8 @@ async function runLive(command, cfg, opts) {
5768
6202
  );
5769
6203
  }
5770
6204
  const built = insertRunnerArgs(runCommand, extraArgs);
5771
- console.log(
5772
- dim(
5773
- `flakefinder: attempt ${attempt}/${maxAttempts}${note ? ` (${note})` : ""} \u2192 ${truncateForLog(built.join(" "))}`
5774
- )
5775
- );
6205
+ const attemptLine = `flakefinder: attempt ${attempt}/${maxAttempts}${note ? ` (${note})` : ""} \u2192 ${truncateForLog(built.join(" "))}`;
6206
+ console.log(opts.color ? `\x1B[2m${attemptLine}\x1B[0m` : attemptLine);
5776
6207
  let code = await spawnCommand(
5777
6208
  built,
5778
6209
  cwd,
@@ -5818,13 +6249,14 @@ async function runLive(command, cfg, opts) {
5818
6249
  console.warn(`flakefinder: ${unrecognizedReason(content)} \u2014 skipped ${file}`);
5819
6250
  continue;
5820
6251
  }
5821
- const { results, warnings } = parser.parse(content, file);
6252
+ const { results, warnings } = parseReport(parser, content, file, cwd, cfg.reportScopes);
5822
6253
  for (const w of warnings) console.warn(`flakefinder: ${parser.name}: ${w}`);
5823
6254
  attempts.push({
5824
6255
  runId,
5825
6256
  timestamp: (/* @__PURE__ */ new Date()).toISOString(),
5826
6257
  source: "live",
5827
6258
  parsedFrom: parser.name,
6259
+ ...parser.name === "junit" ? { reportFile: testFileScope(file, cwd) } : {},
5828
6260
  attempt,
5829
6261
  commitSha,
5830
6262
  results
@@ -5837,24 +6269,30 @@ async function runLive(command, cfg, opts) {
5837
6269
  }
5838
6270
  } finally {
5839
6271
  if (exactDeselect) rmSync3(exactDeselect.dir, { recursive: true, force: true });
6272
+ if (mochaFilterFile) {
6273
+ rmSync3(mochaFilterFile, { force: true });
6274
+ rmdirSync(path10.dirname(mochaFilterFile));
6275
+ }
5840
6276
  process.off("SIGINT", onInterrupt);
5841
6277
  process.off("SIGTERM", onInterrupt);
5842
6278
  }
5843
- const store = new HistoryStore(path7.resolve(cwd, cfg.storeDir));
6279
+ const store = new HistoryStore(path10.resolve(cwd, cfg.storeDir));
5844
6280
  for (const record of attempts) store.append(record);
5845
6281
  store.prune(cfg.maxRuns);
5846
- const all = classifyAll(store.runs(), cfg);
6282
+ const all = classifyAll(store.runs(), cfg, (message) => console.warn(`flakefinder: ${message}`));
5847
6283
  const invocationIds = new Set(attempts.flatMap((r) => r.results.map((t) => t.testId)));
5848
6284
  const verdicts = all.filter((v) => invocationIds.has(v.testId));
5849
- const suiteFlake = usedReportFiles.size === 0 && exitCodes.some((c) => c === 0) && exitCodes.some((c) => c !== 0);
6285
+ const suiteFlake = invocationIds.size === 0 && exitCodes.some((c) => c === 0) && exitCodes.some((c) => c !== 0);
5850
6286
  if (suiteFlake) {
5851
6287
  console.warn(
5852
- "flakefinder: no report files matched \u2014 suite-level verdict only (exits varied across attempts)."
6288
+ "flakefinder: no usable test results \u2014 suite-level verdict only (exits varied across attempts)."
5853
6289
  );
5854
6290
  }
5855
6291
  const lastExit = exitCodes[exitCodes.length - 1] ?? 1;
5856
6292
  const lastRealStatus = /* @__PURE__ */ new Map();
5857
- for (const record of [...attempts].sort((a, b) => a.attempt - b.attempt)) {
6293
+ for (const record of reconcileReportResults(
6294
+ [...attempts].sort((a, b) => a.attempt - b.attempt)
6295
+ )) {
5858
6296
  for (const t of record.results) if (t.status !== "skip") lastRealStatus.set(t.testId, t.status);
5859
6297
  }
5860
6298
  const gated = verdicts.filter(
@@ -5879,22 +6317,17 @@ async function runLive(command, cfg, opts) {
5879
6317
  }
5880
6318
  var SELECTOR_ALIASES = {
5881
6319
  "-t": ["-t", "--testNamePattern"],
5882
- "--grep": ["--grep", "-g", "--fgrep", "-f"],
5883
6320
  "-run": ["-run", "--run"]
5884
6321
  };
5885
- var LITERAL_SELECTORS = /* @__PURE__ */ new Set(["--fgrep", "-f"]);
5886
6322
  function mergeUserSelector(command, extraArgs) {
5887
6323
  const unchanged = { command, extraArgs, userPatterns: [] };
5888
6324
  const flag = extraArgs[0];
5889
6325
  const ours = extraArgs[1];
5890
- if (flag !== "-t" && flag !== "--grep" || ours === void 0 || !ours.startsWith("^")) {
6326
+ if (flag !== "-t" || ours === void 0 || !ours.startsWith("^")) {
5891
6327
  return unchanged;
5892
6328
  }
5893
6329
  const aliases = SELECTOR_ALIASES[flag];
5894
6330
  const { cmd, end } = runnerSegment(command);
5895
- if (flag === "--grep" && command.slice(cmd + 1, end).some((t) => t === "--invert" || t === "-i")) {
5896
- return unchanged;
5897
- }
5898
6331
  const kept = command.slice(0, cmd + 1);
5899
6332
  const userPatterns = [];
5900
6333
  for (let i = cmd + 1; i < end; i++) {
@@ -5915,8 +6348,6 @@ function mergeUserSelector(command, extraArgs) {
5915
6348
  } else {
5916
6349
  value = t.slice(alias.length + 1);
5917
6350
  }
5918
- if (LITERAL_SELECTORS.has(alias)) value = value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
5919
- else if (flag === "--grep") value = value.replace(/^\/(.*)\/[a-z]*$/s, "$1");
5920
6351
  userPatterns.push(value);
5921
6352
  }
5922
6353
  if (userPatterns.length === 0) return unchanged;
@@ -5948,8 +6379,8 @@ function setUpExactDeselect(flags) {
5948
6379
  const ids = deselectedNodeIds(flags);
5949
6380
  if (ids.length === 0) return null;
5950
6381
  try {
5951
- const dir = mkdtempSync(path7.join(tmpdir(), "flakefinder-pytest-"));
5952
- writeFileSync3(path7.join(dir, `${PYTEST_EXACT_PLUGIN_MODULE}.py`), PYTEST_EXACT_PLUGIN_SOURCE);
6382
+ const dir = mkdtempSync(path10.join(tmpdir(), "flakefinder-pytest-"));
6383
+ writeFileSync4(path10.join(dir, `${PYTEST_EXACT_PLUGIN_MODULE}.py`), PYTEST_EXACT_PLUGIN_SOURCE);
5953
6384
  return { env: pytestExactDeselectEnv(ids, dir), dir };
5954
6385
  } catch {
5955
6386
  return null;
@@ -5999,23 +6430,23 @@ function pytestCacheDisabled(command, cwd, env = process.env) {
5999
6430
  else if (t.startsWith("--config-file=")) explicit = t.slice("--config-file=".length);
6000
6431
  });
6001
6432
  if (explicit !== void 0) {
6002
- const text2 = readIfFile(path7.resolve(cwd, explicit));
6433
+ const text2 = readIfFile(path10.resolve(cwd, explicit));
6003
6434
  if (text2 === null) return false;
6004
6435
  const header = PYTEST_CONFIGS.find((c) => explicit.endsWith(c.file))?.section;
6005
6436
  const section = header ? pytestSection(text2, header) : null;
6006
6437
  return sectionDisablesCache(section ?? text2);
6007
6438
  }
6008
- let dir = path7.resolve(cwd);
6439
+ let dir = path10.resolve(cwd);
6009
6440
  for (; ; ) {
6010
6441
  for (const { file, section: header } of PYTEST_CONFIGS) {
6011
- const text2 = readIfFile(path7.join(dir, file));
6442
+ const text2 = readIfFile(path10.join(dir, file));
6012
6443
  if (text2 === null) continue;
6013
6444
  const section = pytestSection(text2, header);
6014
6445
  if (section !== null) return sectionDisablesCache(section);
6015
6446
  if (file === "pytest.ini" || file === ".pytest.ini") return false;
6016
6447
  }
6017
- const parent = path7.dirname(dir);
6018
- if (parent === dir || existsSync5(path7.join(dir, ".git"))) return false;
6448
+ const parent = path10.dirname(dir);
6449
+ if (parent === dir || existsSync6(path10.join(dir, ".git"))) return false;
6019
6450
  dir = parent;
6020
6451
  }
6021
6452
  }
@@ -6023,9 +6454,6 @@ var SELECTOR_BUDGET_CHARS = process.platform === "win32" ? 6e3 : 32768;
6023
6454
  function truncateForLog(line, max = 400) {
6024
6455
  return line.length <= max ? line : `${line.slice(0, max)}\u2026 (+${line.length - max} chars)`;
6025
6456
  }
6026
- function dim(s) {
6027
- return process.stdout.isTTY ? `\x1B[2m${s}\x1B[0m` : s;
6028
- }
6029
6457
  function isPackageManagerWrapper(command) {
6030
6458
  const first = commandBase(command[0] ?? "");
6031
6459
  return first === "npm" || first === "yarn" || first === "pnpm" || first === "bun";
@@ -6053,14 +6481,14 @@ function takesRedirectTarget(token) {
6053
6481
  }
6054
6482
  function isBatchCommand(cmd, cwd, env = process.env) {
6055
6483
  if (/\.(?:cmd|bat)$/i.test(cmd)) return true;
6056
- if (path7.extname(cmd) !== "") return false;
6484
+ if (path10.extname(cmd) !== "") return false;
6057
6485
  const exts = (env.PATHEXT ?? ".COM;.EXE;.BAT;.CMD").split(";").filter(Boolean);
6058
6486
  const hasDir = /[\\/]/.test(cmd);
6059
6487
  const dirs = hasDir ? [""] : [cwd, ...(env.PATH ?? env.Path ?? "").split(";").filter(Boolean)];
6060
6488
  for (const dir of dirs) {
6061
6489
  for (const ext of exts) {
6062
- const candidate = dir ? path7.join(dir, cmd + ext) : path7.resolve(cwd, cmd + ext);
6063
- if (existsSync5(candidate)) return /^\.(?:cmd|bat)$/i.test(ext);
6490
+ const candidate = dir ? path10.join(dir, cmd + ext) : path10.resolve(cwd, cmd + ext);
6491
+ if (existsSync6(candidate)) return /^\.(?:cmd|bat)$/i.test(ext);
6064
6492
  }
6065
6493
  }
6066
6494
  return false;
@@ -6094,14 +6522,6 @@ function shellArgvFor(command, cwd, platform = process.platform) {
6094
6522
  return out;
6095
6523
  }
6096
6524
 
6097
- // src/util/strict-int.ts
6098
- function parseStrictInt(value, min, max) {
6099
- if (!/^-?\d+$/.test(value)) return null;
6100
- const n = Number.parseInt(value, 10);
6101
- if (!Number.isSafeInteger(n) || n < min || n > max) return null;
6102
- return n;
6103
- }
6104
-
6105
6525
  // src/cli/color.ts
6106
6526
  function shouldColor(flag, stream, env = process.env) {
6107
6527
  if (!flag) return false;
@@ -6148,7 +6568,7 @@ function openInBrowser(file, warn = (m) => console.warn(m), platform = process.p
6148
6568
  var PROBLEM_ALWAYS = ["flaky-confirmed", "flaky-retry", "failing", "new-failure"];
6149
6569
  function resolveCfg(g, overrides = {}) {
6150
6570
  if (g.config) {
6151
- return resolveConfig(readConfigFile(path8.resolve(g.cwd, g.config)), overrides);
6571
+ return resolveConfig(readConfigFile(path11.resolve(g.cwd, g.config)), overrides);
6152
6572
  }
6153
6573
  const { config } = loadConfig(g.cwd);
6154
6574
  return resolveConfig(config, overrides);
@@ -6175,10 +6595,10 @@ function ciCommitSha(cwd, env = process.env) {
6175
6595
  return gitSha(cwd);
6176
6596
  }
6177
6597
  function readSnapshot(file) {
6178
- if (!existsSync6(file)) return null;
6598
+ if (!existsSync7(file)) return null;
6179
6599
  let parsed;
6180
6600
  try {
6181
- parsed = JSON.parse(readFileSync7(file, "utf8"));
6601
+ parsed = JSON.parse(readFileSync8(file, "utf8"));
6182
6602
  } catch (err) {
6183
6603
  console.warn(
6184
6604
  `flakefinder: ignoring unreadable verdict snapshot ${file} (${err.message}) \u2014 no baseline this run, every current flake counts as new; it is rewritten below`
@@ -6195,8 +6615,12 @@ function readSnapshot(file) {
6195
6615
  (v) => typeof v === "object" && v !== null && typeof v.testId === "string" && typeof v.classification === "string"
6196
6616
  );
6197
6617
  }
6618
+ function pruneWorkflowBaselines(dir, maxRuns) {
6619
+ const baselines = readdirSync2(dir, { withFileTypes: true }).filter((entry) => entry.isFile() && /^\d+\.json$/.test(entry.name)).map((entry) => entry.name).sort((a, b) => b.length - a.length || b.localeCompare(a));
6620
+ for (const name of baselines.slice(maxRuns)) rmSync4(path11.join(dir, name), { force: true });
6621
+ }
6198
6622
  function storeFor(g, cfg) {
6199
- return new HistoryStore(path8.resolve(g.cwd, cfg.storeDir));
6623
+ return new HistoryStore(path11.resolve(g.cwd, cfg.storeDir));
6200
6624
  }
6201
6625
  function printStoreWarnings(store) {
6202
6626
  for (const w of store.warnings) console.warn(`flakefinder: ${w}`);
@@ -6281,7 +6705,7 @@ async function main(argv) {
6281
6705
  });
6282
6706
  const globals = () => {
6283
6707
  const o = program.opts();
6284
- return { config: o.config, cwd: path8.resolve(o.cwd ?? "."), color: o.color !== false };
6708
+ return { config: o.config, cwd: path11.resolve(o.cwd ?? "."), color: o.color !== false };
6285
6709
  };
6286
6710
  program.command("init").description("detect your test runner and create flakefinder.config.json").option("--force", "overwrite an existing config").option(
6287
6711
  "--runner <runner>",
@@ -6305,14 +6729,14 @@ async function main(argv) {
6305
6729
  exitCode = 2;
6306
6730
  return;
6307
6731
  }
6308
- const configPath = path8.join(g.cwd, CONFIG_FILE_NAME);
6309
- if (existsSync6(configPath) && !opts.force) {
6732
+ const configPath = path11.join(g.cwd, CONFIG_FILE_NAME);
6733
+ if (existsSync7(configPath) && !opts.force) {
6310
6734
  console.error(`flakefinder: ${configPath} already exists (use --force to overwrite)`);
6311
6735
  exitCode = 2;
6312
6736
  return;
6313
6737
  }
6314
6738
  const cfg = { reports: defaultReportsFor(runner), runner };
6315
- writeFileSync4(configPath, `${JSON.stringify(cfg, null, 2)}
6739
+ writeFileSync5(configPath, `${JSON.stringify(cfg, null, 2)}
6316
6740
  `, "utf8");
6317
6741
  console.log(`created ${configPath} (runner: ${runner})`);
6318
6742
  printSetupHints(runner);
@@ -6365,12 +6789,14 @@ async function main(argv) {
6365
6789
  const cfg = resolveCfg(g, overrides);
6366
6790
  const storeWarnings = [];
6367
6791
  const unsubscribe = subscribeStoreWarnings((w) => storeWarnings.push(w));
6792
+ const color = shouldColor(g.color, process.stdout);
6368
6793
  let result;
6369
6794
  try {
6370
6795
  result = await runLive(command, cfg, {
6371
6796
  retries: retries ?? cfg.liveRetries,
6372
6797
  cwd: g.cwd,
6373
- applyQuarantine: opts.quarantine !== false
6798
+ applyQuarantine: opts.quarantine !== false,
6799
+ color
6374
6800
  });
6375
6801
  } finally {
6376
6802
  unsubscribe();
@@ -6385,7 +6811,7 @@ async function main(argv) {
6385
6811
  }
6386
6812
  console.log(
6387
6813
  renderTerminal(result.verdicts, {
6388
- color: shouldColor(g.color, process.stdout),
6814
+ color,
6389
6815
  flakesOnly: false
6390
6816
  })
6391
6817
  );
@@ -6412,10 +6838,10 @@ async function main(argv) {
6412
6838
  const targets = files.length > 0 ? [] : matchGlobs(g.cwd, cfg.reports);
6413
6839
  const seen = /* @__PURE__ */ new Set();
6414
6840
  for (const file of files) {
6415
- const resolved = path8.resolve(g.cwd, file);
6841
+ const resolved = path11.resolve(g.cwd, file);
6416
6842
  let identity = resolved;
6417
6843
  try {
6418
- identity = realpathSync2.native(resolved);
6844
+ identity = realpathSync3.native(resolved);
6419
6845
  } catch {
6420
6846
  }
6421
6847
  if (seen.has(identity)) continue;
@@ -6429,6 +6855,7 @@ async function main(argv) {
6429
6855
  exitCode = 2;
6430
6856
  return;
6431
6857
  }
6858
+ validateReportScopes(targets, g.cwd, cfg.reportScopes);
6432
6859
  let runId = randomUUID2();
6433
6860
  if (opts.runId != null) {
6434
6861
  if (!RUN_ID_RE.test(opts.runId)) {
@@ -6459,7 +6886,7 @@ async function main(argv) {
6459
6886
  warnings++;
6460
6887
  continue;
6461
6888
  }
6462
- const parsed = parser.parse(content, file);
6889
+ const parsed = parseReport(parser, content, file, g.cwd, cfg.reportScopes);
6463
6890
  warnings += parsed.warnings.length;
6464
6891
  for (const w of parsed.warnings) console.warn(`flakefinder: ${w}`);
6465
6892
  const record = {
@@ -6467,6 +6894,7 @@ async function main(argv) {
6467
6894
  timestamp: (/* @__PURE__ */ new Date()).toISOString(),
6468
6895
  source: opts.source,
6469
6896
  parsedFrom: parser.name,
6897
+ ...parser.name === "junit" ? { reportFile: testFileScope(file, g.cwd) } : {},
6470
6898
  attempt,
6471
6899
  commitSha: gitSha(g.cwd),
6472
6900
  results: parsed.results
@@ -6484,6 +6912,13 @@ async function main(argv) {
6484
6912
  }
6485
6913
  store.prune(cfg.maxRuns);
6486
6914
  printStoreWarnings(store);
6915
+ reconcileReportResults(
6916
+ store.runs().filter((r) => r.runId === runId && r.attempt === attempt),
6917
+ (message) => {
6918
+ warnings++;
6919
+ console.warn(`flakefinder: ${message}`);
6920
+ }
6921
+ );
6487
6922
  console.log(
6488
6923
  `ingested ${total} test result(s) from ${used}/${targets.length} file(s) (${warnings} warning(s)) \u2192 ${store.path}`
6489
6924
  );
@@ -6501,7 +6936,11 @@ async function main(argv) {
6501
6936
  }
6502
6937
  const cfg = resolveCfg(g);
6503
6938
  const store = storeFor(g, cfg);
6504
- const verdicts = classifyAll(store.runs(), cfg);
6939
+ const verdicts = classifyAll(
6940
+ store.runs(),
6941
+ cfg,
6942
+ (message) => console.warn(`flakefinder: ${message}`)
6943
+ );
6505
6944
  printStoreWarnings(store);
6506
6945
  if (opts.format === "json") {
6507
6946
  console.log(renderJson(verdicts, cfg));
@@ -6540,9 +6979,13 @@ async function main(argv) {
6540
6979
  }
6541
6980
  const cfg = resolveCfg(g);
6542
6981
  const store = storeFor(g, cfg);
6543
- const verdicts = classifyAll(store.runs(), cfg);
6982
+ const verdicts = classifyAll(
6983
+ store.runs(),
6984
+ cfg,
6985
+ (message) => console.warn(`flakefinder: ${message}`)
6986
+ );
6544
6987
  printStoreWarnings(store);
6545
- const runs = store.runs().slice(-50).map((r) => ({
6988
+ const runs = reconcileReportResults(store.runs()).filter((r) => r.results.length > 0).slice(-50).map((r) => ({
6546
6989
  runId: r.runId,
6547
6990
  timestamp: r.timestamp,
6548
6991
  commitSha: r.commitSha,
@@ -6555,10 +6998,10 @@ async function main(argv) {
6555
6998
  verdicts,
6556
6999
  runs
6557
7000
  });
6558
- const out = path8.resolve(g.cwd, opts.out);
7001
+ const out = path11.resolve(g.cwd, opts.out);
6559
7002
  try {
6560
- mkdirSync2(path8.dirname(out), { recursive: true });
6561
- writeFileSync4(out, html, "utf8");
7003
+ mkdirSync3(path11.dirname(out), { recursive: true });
7004
+ writeFileSync5(out, html, "utf8");
6562
7005
  } catch (err) {
6563
7006
  const e = err;
6564
7007
  console.error(
@@ -6573,7 +7016,7 @@ async function main(argv) {
6573
7016
  program.command("quarantine").description("manage the quarantine list (tests excluded from runs)").argument("<action>", "list | add | remove | prune").argument("[testId]", "testId for add/remove").option("--reason <text>", "reason recorded with the entry", "flaky").action((action, testId, opts) => {
6574
7017
  const g = globals();
6575
7018
  const cfg = resolveCfg(g);
6576
- const qPath = path8.resolve(g.cwd, cfg.quarantineFile);
7019
+ const qPath = path11.resolve(g.cwd, cfg.quarantineFile);
6577
7020
  const qm = new QuarantineManager(qPath);
6578
7021
  if (action === "list") {
6579
7022
  const entries = qm.list();
@@ -6592,6 +7035,8 @@ async function main(argv) {
6592
7035
  console.log(
6593
7036
  `note: runner "${runner}" has no per-test exclusion \u2014 entries are informational only`
6594
7037
  );
7038
+ } else if (runner === "mocha") {
7039
+ console.log("next run will apply quarantine alongside your Mocha filters");
6595
7040
  } else {
6596
7041
  console.log(`next run will add: ${esc(exclusionArgs(runner, entries, g.cwd).join(" "))}`);
6597
7042
  }
@@ -6603,7 +7048,8 @@ async function main(argv) {
6603
7048
  exitCode = 2;
6604
7049
  return;
6605
7050
  }
6606
- const verdicts = classifyAll(storeFor(g, cfg).runs(), cfg);
7051
+ const history = storeFor(g, cfg).runs();
7052
+ const verdicts = classifyAll(history, cfg);
6607
7053
  const v = verdicts.find((x) => x.testId === testId);
6608
7054
  if (!v) {
6609
7055
  console.error(
@@ -6612,6 +7058,14 @@ async function main(argv) {
6612
7058
  exitCode = 1;
6613
7059
  return;
6614
7060
  }
7061
+ const runner = cfg.runner === "auto" ? detectRunner(g.cwd) : cfg.runner;
7062
+ if ((runner === "jest" || runner === "mocha") && ambiguousQuarantineName([v.name], history)) {
7063
+ console.error(
7064
+ `flakefinder: quarantine cannot exclude ${JSON.stringify(v.name)} in only one file or report scope with ${runner}`
7065
+ );
7066
+ exitCode = 2;
7067
+ return;
7068
+ }
6615
7069
  qm.add({
6616
7070
  testId,
6617
7071
  suite: v.suite,
@@ -6677,6 +7131,7 @@ async function main(argv) {
6677
7131
  }
6678
7132
  const store = storeFor(g, cfg);
6679
7133
  const runId = randomUUID2();
7134
+ validateReportScopes(targets, g.cwd, cfg.reportScopes);
6680
7135
  const commitSha = ciCommitSha(g.cwd);
6681
7136
  let ingestedFiles = 0;
6682
7137
  for (const file of targets) {
@@ -6692,7 +7147,7 @@ async function main(argv) {
6692
7147
  console.warn(`flakefinder: ${unrecognizedReason(content)} \u2014 skipped ${file}`);
6693
7148
  continue;
6694
7149
  }
6695
- const parsed = parser.parse(content, file);
7150
+ const parsed = parseReport(parser, content, file, g.cwd, cfg.reportScopes);
6696
7151
  for (const w of parsed.warnings) console.warn(`flakefinder: ${w}`);
6697
7152
  if (parsed.results.length === 0) {
6698
7153
  console.warn(`flakefinder: ${parser.name}: no test results in ${file}`);
@@ -6703,6 +7158,7 @@ async function main(argv) {
6703
7158
  timestamp: (/* @__PURE__ */ new Date()).toISOString(),
6704
7159
  source: "action",
6705
7160
  parsedFrom: parser.name,
7161
+ ...parser.name === "junit" ? { reportFile: testFileScope(file, g.cwd) } : {},
6706
7162
  attempt: 1,
6707
7163
  commitSha,
6708
7164
  results: parsed.results
@@ -6715,7 +7171,11 @@ async function main(argv) {
6715
7171
  return;
6716
7172
  }
6717
7173
  if (ingestedFiles > 0) store.prune(cfg.maxRuns);
6718
- const verdicts = classifyAll(store.runs(), cfg);
7174
+ const verdicts = classifyAll(
7175
+ store.runs(),
7176
+ cfg,
7177
+ (message) => console.warn(`flakefinder: ${message}`)
7178
+ );
6719
7179
  printStoreWarnings(store);
6720
7180
  console.log(renderTerminal(verdicts, { color: false, flakesOnly: false }));
6721
7181
  for (const v of verdicts.filter((x) => x.classification.startsWith("flaky-"))) {
@@ -6723,14 +7183,24 @@ async function main(argv) {
6723
7183
  `::warning title=flakefinder::${ghEscape(escapeControlChars(`${redact(v.suite)} :: ${redact(v.name)} (${v.classification}, score ${v.flakeScore})`))}`
6724
7184
  );
6725
7185
  }
6726
- const reportPath = path8.resolve(g.cwd, "flakefinder-report.json");
6727
- writeFileSync4(reportPath, renderJson(verdicts, cfg), "utf8");
7186
+ const reportPath = path11.resolve(g.cwd, "flakefinder-report.json");
7187
+ writeFileSync5(reportPath, renderJson(verdicts, cfg), "utf8");
6728
7188
  console.log(`json report \u2192 ${reportPath}`);
6729
- const snap = snapshotPath(path8.resolve(g.cwd, cfg.storeDir));
6730
- const previous = readSnapshot(snap);
7189
+ const storeDir = path11.resolve(g.cwd, cfg.storeDir);
7190
+ const snap = snapshotPath(storeDir);
7191
+ const workflowRunId = process.env.GITHUB_RUN_ID?.trim() ?? "";
7192
+ const baselineDir = path11.join(storeDir, "ci-baselines");
7193
+ const baselineFile = /^\d+$/.test(workflowRunId) ? path11.join(baselineDir, `${workflowRunId}.json`) : null;
7194
+ const baseline = baselineFile ? resolveBaseline(storeDir, workflowRunId, baselineFile) : null;
7195
+ for (const warning of baseline?.warnings ?? []) console.warn(`flakefinder: ${warning}`);
7196
+ const previous = baseline ? baseline.previous : readSnapshot(snap);
6731
7197
  const newFlakes = computeNewFlakes(verdicts, previous);
6732
- mkdirSync2(path8.dirname(snap), { recursive: true });
6733
- writeFileSync4(snap, JSON.stringify(verdicts), "utf8");
7198
+ mkdirSync3(path11.dirname(snap), { recursive: true });
7199
+ if (baselineFile && baseline?.source !== "earlier-attempt") {
7200
+ recordBaseline(storeDir, workflowRunId, previous, baselineFile);
7201
+ pruneWorkflowBaselines(baselineDir, cfg.maxRuns);
7202
+ }
7203
+ writeFileSync5(snap, JSON.stringify(verdicts), "utf8");
6734
7204
  const gl = gitlabEnvFromProcess();
6735
7205
  if (gl) {
6736
7206
  try {