@cleocode/core 2026.11.23 → 2026.12.1-rc.ci.741

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,4 +1,4 @@
1
1
  {
2
2
  "schema": 2,
3
- "sourceHash": "cbcc2d31adb5373e2235385a59a36016abd986a3ce3067a6be6f4dd0c640db20"
3
+ "sourceHash": "c1d15584dc6e11bf7dbf859bda1e2f30325668ff0dc99c5f18db867bf1b3fa4a"
4
4
  }
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "schema": 1,
3
- "gitHead": "ba5161420518105e35ddb8c0018ad310ac13fe48",
4
- "builtAt": "2026-11-29T12:34:29.072Z",
3
+ "gitHead": "9aa0fec0feb482d84119e8f7ff65f99add1f17b8",
4
+ "builtAt": "2026-12-06T11:40:02.920Z",
5
5
  "linkedWorktree": null
6
6
  }
@@ -54,6 +54,14 @@
54
54
  * accepted that a later change weakening a check also releases the tasks
55
55
  * waiting behind it. A failure that is the PR's still refuses.
56
56
  *
57
+ * A sixth (T14696, owner decision 2026-11-29): a merge commit whose run FAILED
58
+ * only on named tests may be stood in for when a later merged PR, whose task
59
+ * carries met non-author verdicts on that PR's head, changed each of those
60
+ * test files and names each test by file and describe chain in that task's
61
+ * own text or verdict reasons ({@link proveFlakeFixes}). Only a later green run that
62
+ * includes each proving PR and passed the same test files stands in; the
63
+ * current-head route is never opened by it. Anything else still refuses.
64
+ *
57
65
  * @task T12634
58
66
  */
59
67
  import type { EvidenceAtom, EvidenceValidationContext } from '@cleocode/contracts';
@@ -141,7 +149,8 @@ export interface EvaluateMergeCommitChecksOptions {
141
149
  /**
142
150
  * The merge commit's failures were not the PR's: all inherited from its
143
151
  * base (T13453), or only the flaky-quarantine budget with every test passing
144
- * (T13809). The descendant may stand in for a FAILED required check too.
152
+ * (T13809), or tests a later merged PR proved flaky and fixed (T14696).
153
+ * The descendant may stand in for a FAILED required check too.
145
154
  */
146
155
  inheritedFailures?: boolean;
147
156
  /**
@@ -283,6 +292,12 @@ export interface ResolveCiEvidenceOptions {
283
292
  * be read (T13809). Defaults to `gh api repos/{owner}/{repo}/actions/jobs/<id>/logs`.
284
293
  */
285
294
  fetchJobLog?: (jobId: number, cwd: string) => Promise<string | null>;
295
+ /**
296
+ * Merged-PR and verdict lookups proving a merge commit's failing tests flaky
297
+ * and fixed by a later PR (T14696). Defaults to {@link defaultFlakeFixProof}
298
+ * on the store root.
299
+ */
300
+ flakeFixProof?: FlakeFixProofDeps;
286
301
  /**
287
302
  * Messages of one Actions job's failure-level check-run annotations, or null
288
303
  * when they cannot be read (T14693). GitHub records a lost runner or a job
@@ -767,6 +782,133 @@ export declare function failedStepOf(log: string): string | null;
767
782
  * @task T14252
768
783
  */
769
784
  export declare function blockingTestIds(log: string): string[];
785
+ /** One test that failed a merge-commit job (T14696). */
786
+ export interface FailingTest {
787
+ /** The failing job's name. */
788
+ job: string;
789
+ /** The failing job's check-run id on the merge commit. */
790
+ mergeRunId: number;
791
+ /** The vitest project label printed before the file, when the run has projects. */
792
+ project?: string;
793
+ /** The test file as vitest printed it (relative to its project root). */
794
+ file: string;
795
+ /** The test's title: its describe chain and name, joined by ` > `. */
796
+ title: string;
797
+ }
798
+ /** A failing test that a later merged, reviewer-verified PR proved flaky and fixed (T14696). */
799
+ export interface FlakeFix extends FailingTest {
800
+ /** The PR that names the test and fixed it. */
801
+ proofPr: number;
802
+ /** That PR's task whose criteria carry met verdicts on the PR's head. */
803
+ proofTask: string;
804
+ /** The PR's merge commit on the default branch. */
805
+ proofMergeSha: string;
806
+ }
807
+ /** A PR merged into the default branch after the merge commit (T14696). */
808
+ export interface LaterMergedPr {
809
+ /** PR number. */
810
+ number: number;
811
+ /** The first-parent commit it merged as. */
812
+ mergeCommitSha: string;
813
+ /** Its final head, which reviewer verdicts are bound to. */
814
+ headSha: string;
815
+ /** PR title. */
816
+ title: string;
817
+ /** PR body, with its `Closes:` / `Refs:` lines. */
818
+ body: string;
819
+ /** Repository paths the PR changed. */
820
+ files: string[];
821
+ }
822
+ /** I/O for the flake-fix proof (T14696); see {@link proveFlakeFixes}. */
823
+ export interface FlakeFixProofDeps {
824
+ /** The PRs merged as these default-branch commits, oldest first; null when they cannot be read. */
825
+ listMergedPrsAt: (shas: readonly string[], cwd: string) => Promise<LaterMergedPr[] | null>;
826
+ /**
827
+ * The task's own description and criteria, and the reasons of its met
828
+ * verdicts, as one text when every criterion `acs` names carries a met
829
+ * non-author verdict on `pr.headSha`; null when it does not (or the task
830
+ * is unknown). Never the PR's title or body, which anyone can write.
831
+ */
832
+ verdictBackedTask: (taskId: string, pr: LaterMergedPr, acs: readonly string[]) => Promise<string | null>;
833
+ }
834
+ /** Result of {@link proveFlakeFixes}. */
835
+ export type FlakeFixResult = {
836
+ ok: true;
837
+ fixes: FlakeFix[];
838
+ } | {
839
+ ok: false;
840
+ reason: string;
841
+ };
842
+ /**
843
+ * The tests that failed a job and decided it (T14696), from its log: vitest's
844
+ * `FAIL [<project>] <file> > <title>` lines after its re-run marker when it
845
+ * re-ran (T13145). Null unless the log is a clean test failure: the run's own
846
+ * summary block ({@link runSummary}) shows failed tests, no error escaped a
847
+ * test, no worker died, and the named tests and files match its counts.
848
+ *
849
+ * @param log - The job's plain-text log (ANSI colour codes allowed).
850
+ * @returns The failing tests, or null.
851
+ * @task T14696
852
+ */
853
+ export declare function failingTestsInLog(log: string): Array<{
854
+ project?: string;
855
+ file: string;
856
+ title: string;
857
+ }> | null;
858
+ /**
859
+ * Every test that failed the merge commit's run (T14696): each failing job of
860
+ * a pinned workflow (the required aggregate and workflow runs follow the jobs
861
+ * they need) must have failed on named tests alone ({@link failingTestsInLog}).
862
+ * A pending, cancelled or timed-out job, an unreadable log, or a failure that
863
+ * is not a clean test failure refuses.
864
+ *
865
+ * @param checks - Checks fetched for `sha`.
866
+ * @param sha - The merge commit.
867
+ * @param required - Required check names.
868
+ * @param pins - Required-name to app/workflow pin.
869
+ * @param fetchJobLog - Plain-text log of one job.
870
+ * @param cwd - Repository work tree for `gh`.
871
+ * @returns The failing tests, or why the run failed otherwise.
872
+ * @task T14696
873
+ */
874
+ export declare function failingTestsOn(checks: readonly CommitCheck[], sha: string, required: readonly string[], pins: Record<string, RequiredCheckPinSpec>, fetchJobLog: NonNullable<ResolveCiEvidenceOptions['fetchJobLog']>, cwd: string): Promise<{
875
+ ok: true;
876
+ tests: FailingTest[];
877
+ } | {
878
+ ok: false;
879
+ reason: string;
880
+ }>;
881
+ /**
882
+ * Prove every failing test flaky and fixed by a later merged PR (T14696,
883
+ * owner decision 2026-11-29): a PR merged into the default branch after the
884
+ * merge commit that changed the test file itself, one of whose `Closes:` /
885
+ * `Refs:` tasks carries met non-author verdicts for every criterion the line
886
+ * names on the PR's head, and whose own description, criteria or met verdict
887
+ * reasons name the test by file and full describe chain. The PR's title and
888
+ * body never count: an unrelated PR could mention a flake it did not fix. A
889
+ * test no such PR proves refuses.
890
+ * The stand-in must then include each proving PR and pass the same test files
891
+ * (checked by {@link findGreenDescendant}).
892
+ *
893
+ * @param failing - The merge commit's failing tests ({@link failingTestsOn}).
894
+ * @param laterShas - First-parent default-branch commits after the merge, oldest first.
895
+ * @param deps - Merged-PR and verdict lookups.
896
+ * @param cwd - Repository work tree for `gh`.
897
+ * @returns A proving PR per failing test, or the tests left unproven.
898
+ * @task T14696
899
+ */
900
+ export declare function proveFlakeFixes(failing: readonly FailingTest[], laterShas: readonly string[], deps: FlakeFixProofDeps, cwd: string): Promise<FlakeFixResult>;
901
+ /**
902
+ * The default {@link FlakeFixProofDeps} (T14696): merged PRs and their changed
903
+ * files via `gh api` (`commits/<sha>/pulls`, `pulls/<n>/files`), verdicts and
904
+ * task text from the store at `storeRoot`.
905
+ *
906
+ * @param storeRoot - Project root holding the task store.
907
+ * @param gh - One read-only `gh api` GET, null on failure; defaults to `gh api`.
908
+ * @returns The lookups.
909
+ * @task T14696
910
+ */
911
+ export declare function defaultFlakeFixProof(storeRoot: string, gh?: (path: string, cwd: string) => unknown): FlakeFixProofDeps;
770
912
  /**
771
913
  * Whether a later commit's CI failed before any test ran (T13809): every
772
914
  * failing job's log is readable and failed in a setup action step
@@ -829,6 +971,8 @@ export interface FindGreenDescendantInput {
829
971
  firstParentOf?: NonNullable<ResolveCiEvidenceOptions['firstParentOf']>;
830
972
  /** Log of one job (T13809: the quarantine-budget check); absent = never classify. */
831
973
  fetchJobLog?: NonNullable<ResolveCiEvidenceOptions['fetchJobLog']>;
974
+ /** Proof that a failing test was a flake a later PR fixed (T14696); absent = never. */
975
+ flakeFixProof?: FlakeFixProofDeps;
832
976
  /** Annotations of one job (T14693: a lost runner or timeout); absent = never read. */
833
977
  fetchJobAnnotations?: NonNullable<ResolveCiEvidenceOptions['fetchJobAnnotations']>;
834
978
  /** When the next default-branch commit after the merge landed (T14026); absent = unknown. */
@@ -873,14 +1017,18 @@ export type FindGreenDescendantResult = {
873
1017
  }>;
874
1018
  /** The merge commit's failures tested nothing: runner cancellations or worker crashes (T14049, T14074). */
875
1019
  untested?: UntestedJobFailure[];
1020
+ /** The merge commit's failing tests a later merged PR proved flaky and fixed (T14696). */
1021
+ flakeFixed?: FlakeFix[];
876
1022
  /** Later runs the search looked past, and why (T14086). */
877
1023
  passedOver?: PassedOverRun[];
878
1024
  /**
879
1025
  * What was proven before the walk (T14434), for the caller whose
880
1026
  * re-judgement with this stand-in still fails (a required check that
881
1027
  * never ran on the merge commit): the current-head stand-in may be tried.
1028
+ * Absent for a flake fix (T14696), which only a stand-in that passed the
1029
+ * fixed test files closes.
882
1030
  */
883
- cleared: ClearedMerge;
1031
+ cleared?: ClearedMerge;
884
1032
  } | {
885
1033
  ok: false;
886
1034
  reason: string;
@@ -917,8 +1065,11 @@ export interface ClearedMerge {
917
1065
  * The stand-in's CI tested the DESCENDANT's tree, not the merge tree. It is
918
1066
  * accepted only when that difference cannot matter to the PR:
919
1067
  * - the merge commit must be superseded, not failed ({@link supersededOnMerge}),
920
- * unless its failures were inherited from main ({@link inheritedOnMerge}) or
921
- * were only the flaky-quarantine budget ({@link nonTestFailuresOn}, T13809);
1068
+ * unless its failures were inherited from main ({@link inheritedOnMerge}),
1069
+ * were only the flaky-quarantine budget ({@link nonTestFailuresOn}, T13809),
1070
+ * or were tests a later merged PR proved flaky and fixed
1071
+ * ({@link proveFlakeFixes}, T14696): then only a candidate that includes
1072
+ * every proving PR and passed the same test files stands in;
922
1073
  * - the PR's own final head (`prHeadSha`) must have a green latest
923
1074
  * `pull_request` run for every superseded check — a later fix on main
924
1075
  * never rescues a broken PR;
@@ -54,6 +54,14 @@
54
54
  * accepted that a later change weakening a check also releases the tasks
55
55
  * waiting behind it. A failure that is the PR's still refuses.
56
56
  *
57
+ * A sixth (T14696, owner decision 2026-11-29): a merge commit whose run FAILED
58
+ * only on named tests may be stood in for when a later merged PR, whose task
59
+ * carries met non-author verdicts on that PR's head, changed each of those
60
+ * test files and names each test by file and describe chain in that task's
61
+ * own text or verdict reasons ({@link proveFlakeFixes}). Only a later green run that
62
+ * includes each proving PR and passed the same test files stands in; the
63
+ * current-head route is never opened by it. Anything else still refuses.
64
+ *
57
65
  * @task T12634
58
66
  */
59
67
  import { execFileSync } from 'node:child_process';
@@ -1319,6 +1327,264 @@ export function blockingTestIds(log) {
1319
1327
  }
1320
1328
  return [...ids].sort();
1321
1329
  }
1330
+ /** `[<project>] <file> > <title>`, for a reason. */
1331
+ const describeTest = (t) => `${t.project ? `${t.project} ` : ''}${t.file} > ${t.title}`;
1332
+ /**
1333
+ * A log without GitHub's echo of its error annotations (T14696): each
1334
+ * `##[error]` line and the untimestamped lines it continues on. The echo
1335
+ * re-prints a failure's stack (` ❯ file:line`) after vitest's summary, where
1336
+ * it would read as test output ({@link runSummary}).
1337
+ */
1338
+ function withoutAnnotationEcho(text) {
1339
+ let echo = false;
1340
+ return text
1341
+ .split('\n')
1342
+ .filter((line) => {
1343
+ if (line.includes('##[error]'))
1344
+ echo = true;
1345
+ else if (/^\d{4}-\d\d-\d\dT\S+Z/.test(line))
1346
+ echo = false;
1347
+ return !echo;
1348
+ })
1349
+ .join('\n');
1350
+ }
1351
+ /**
1352
+ * The tests that failed a job and decided it (T14696), from its log: vitest's
1353
+ * `FAIL [<project>] <file> > <title>` lines after its re-run marker when it
1354
+ * re-ran (T13145). Null unless the log is a clean test failure: the run's own
1355
+ * summary block ({@link runSummary}) shows failed tests, no error escaped a
1356
+ * test, no worker died, and the named tests and files match its counts.
1357
+ *
1358
+ * @param log - The job's plain-text log (ANSI colour codes allowed).
1359
+ * @returns The failing tests, or null.
1360
+ * @task T14696
1361
+ */
1362
+ export function failingTestsInLog(log) {
1363
+ const text = withoutAnnotationEcho(log.replace(/\u001b\[[0-9;]*m/g, ''));
1364
+ if (/Unhandled (Errors?|Rejection)|\bErrors\s{2,}\d/.test(text) || RUN_DIED.test(text))
1365
+ return null;
1366
+ const summary = runSummary(text);
1367
+ if (summary === null || summary.failedTests === 0)
1368
+ return null;
1369
+ const rerun = RERUN_MARKER.exec(text);
1370
+ const decided = rerun ? text.slice(rerun.index) : text;
1371
+ const failing = new Map();
1372
+ for (const m of decided.matchAll(/\bFAIL\s{2,}(?:(\S+)\s+)?(\S+\.(?:test|spec)\.[cm]?[jt]sx?) > (.+)$/gm)) {
1373
+ // The same relative path can sit in two vitest projects: the project is part of the key.
1374
+ const entry = {
1375
+ ...(m[1] ? { project: m[1] } : {}),
1376
+ file: m[2] ?? '',
1377
+ title: (m[3] ?? '').replace(/\s+/g, ' ').trim(),
1378
+ };
1379
+ failing.set(`${entry.project ?? ''}\u0000${entry.file}\u0000${entry.title}`, entry);
1380
+ }
1381
+ if (failing.size !== summary.failedTests)
1382
+ return null;
1383
+ const files = new Set([...failing.values()].map((f) => `${f.project ?? ''}\u0000${f.file}`));
1384
+ if (files.size !== summary.failedFiles)
1385
+ return null;
1386
+ return [...failing.values()];
1387
+ }
1388
+ /**
1389
+ * Every test that failed the merge commit's run (T14696): each failing job of
1390
+ * a pinned workflow (the required aggregate and workflow runs follow the jobs
1391
+ * they need) must have failed on named tests alone ({@link failingTestsInLog}).
1392
+ * A pending, cancelled or timed-out job, an unreadable log, or a failure that
1393
+ * is not a clean test failure refuses.
1394
+ *
1395
+ * @param checks - Checks fetched for `sha`.
1396
+ * @param sha - The merge commit.
1397
+ * @param required - Required check names.
1398
+ * @param pins - Required-name to app/workflow pin.
1399
+ * @param fetchJobLog - Plain-text log of one job.
1400
+ * @param cwd - Repository work tree for `gh`.
1401
+ * @returns The failing tests, or why the run failed otherwise.
1402
+ * @task T14696
1403
+ */
1404
+ export async function failingTestsOn(checks, sha, required, pins, fetchJobLog, cwd) {
1405
+ const tests = [];
1406
+ for (const c of latestRuns(checks, sha, pinnedScope(required, pins))) {
1407
+ if (c.source === 'workflow-run' || required.includes(c.name))
1408
+ continue;
1409
+ if (c.status !== 'completed')
1410
+ return { ok: false, reason: `${c.name}: pending` };
1411
+ if (c.conclusion === 'success' || c.conclusion === 'skipped')
1412
+ continue;
1413
+ const log = c.conclusion === 'failure' ? await fetchJobLog(c.id, cwd) : null;
1414
+ const failed = log === null ? null : failingTestsInLog(log);
1415
+ if (failed === null)
1416
+ return { ok: false, reason: `${c.name}: ${c.conclusion} without a clean test failure` };
1417
+ tests.push(...failed.map((t) => ({ job: c.name, mergeRunId: c.id, ...t })));
1418
+ }
1419
+ return tests.length > 0
1420
+ ? { ok: true, tests }
1421
+ : { ok: false, reason: `no test failed on ${sha.slice(0, 12)}` };
1422
+ }
1423
+ /** Whitespace and ` > ` separators normalised, for matching a test's title in prose. */
1424
+ const normChain = (text) => text
1425
+ .replace(/\s*>\s*/g, ' > ')
1426
+ .replace(/\s+/g, ' ')
1427
+ .trim();
1428
+ /** Whether `text` names the test: its file path and its full describe chain and name (T14696). */
1429
+ function namesTest(text, test) {
1430
+ const flat = normChain(text);
1431
+ return flat.includes(test.file) && flat.includes(normChain(test.title));
1432
+ }
1433
+ /** Whether the PR changed the test file itself (T14696). */
1434
+ function changedTestFile(pr, test) {
1435
+ return pr.files.some((path) => path === test.file || path.endsWith(`/${test.file}`));
1436
+ }
1437
+ /**
1438
+ * Prove every failing test flaky and fixed by a later merged PR (T14696,
1439
+ * owner decision 2026-11-29): a PR merged into the default branch after the
1440
+ * merge commit that changed the test file itself, one of whose `Closes:` /
1441
+ * `Refs:` tasks carries met non-author verdicts for every criterion the line
1442
+ * names on the PR's head, and whose own description, criteria or met verdict
1443
+ * reasons name the test by file and full describe chain. The PR's title and
1444
+ * body never count: an unrelated PR could mention a flake it did not fix. A
1445
+ * test no such PR proves refuses.
1446
+ * The stand-in must then include each proving PR and pass the same test files
1447
+ * (checked by {@link findGreenDescendant}).
1448
+ *
1449
+ * @param failing - The merge commit's failing tests ({@link failingTestsOn}).
1450
+ * @param laterShas - First-parent default-branch commits after the merge, oldest first.
1451
+ * @param deps - Merged-PR and verdict lookups.
1452
+ * @param cwd - Repository work tree for `gh`.
1453
+ * @returns A proving PR per failing test, or the tests left unproven.
1454
+ * @task T14696
1455
+ */
1456
+ export async function proveFlakeFixes(failing, laterShas, deps, cwd) {
1457
+ const prs = laterShas.length > 0 ? await deps.listMergedPrsAt(laterShas, cwd) : [];
1458
+ if (prs === null)
1459
+ return { ok: false, reason: 'the PRs merged after it could not be read' };
1460
+ const { parseMergeDirectives } = await import('../tasks/merge-close.js');
1461
+ const open = [...failing];
1462
+ const fixes = [];
1463
+ for (const pr of prs) {
1464
+ for (const line of parseMergeDirectives(pr.body).directives) {
1465
+ if (open.length === 0)
1466
+ break;
1467
+ const touched = open.filter((t) => changedTestFile(pr, t));
1468
+ if (touched.length === 0)
1469
+ continue;
1470
+ const taskText = await deps.verdictBackedTask(line.taskId, pr, line.acs);
1471
+ if (taskText === null)
1472
+ continue;
1473
+ for (const test of touched.filter((t) => namesTest(taskText, t))) {
1474
+ fixes.push({
1475
+ ...test,
1476
+ proofPr: pr.number,
1477
+ proofTask: line.taskId,
1478
+ proofMergeSha: pr.mergeCommitSha,
1479
+ });
1480
+ open.splice(open.indexOf(test), 1);
1481
+ }
1482
+ }
1483
+ }
1484
+ return open.length === 0
1485
+ ? { ok: true, fixes }
1486
+ : {
1487
+ ok: false,
1488
+ reason: `no later merged PR changed ${open.map(describeTest).join(', ')} with a task that names ` +
1489
+ 'the test and has met reviewer verdicts, so it is not shown flaky and fixed',
1490
+ };
1491
+ }
1492
+ /**
1493
+ * Why a stand-in does not show each flake fixed (T14696), or null when it
1494
+ * does: the stand-in's latest run of the job that failed must have succeeded
1495
+ * and its log must show the test file passing.
1496
+ */
1497
+ async function flakeFixNotShown(checks, sha, fixes, scope, fetchJobLog, cwd) {
1498
+ const runs = latestRuns(checks, sha, scope);
1499
+ for (const fix of fixes) {
1500
+ const run = runs.find((c) => c.name === fix.job && c.source === 'check-run');
1501
+ const log = run?.conclusion === 'success' ? await fetchJobLog(run.id, cwd) : null;
1502
+ const esc = (v) => v.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
1503
+ // Keyed on the project too: the same relative path in another project is another file.
1504
+ const project = fix.project ? `${esc(fix.project)}\\s+` : '';
1505
+ const passed = log !== null &&
1506
+ new RegExp(`✓\\s+${project}${esc(fix.file)}\\s`).test(log.replace(/\u001b\[[0-9;]*m/g, ''));
1507
+ if (!passed)
1508
+ return (`${describeTest(fix).split(' > ')[0]} did not pass in ${fix.job} on ${sha.slice(0, 12)}, ` +
1509
+ `so it does not show the flake PR #${fix.proofPr} fixed as fixed`);
1510
+ }
1511
+ return null;
1512
+ }
1513
+ /** Pages of a PR's changed files read (100 each; GitHub lists at most 3000). */
1514
+ const PR_FILES_MAX_PAGES = 30;
1515
+ /**
1516
+ * The default {@link FlakeFixProofDeps} (T14696): merged PRs and their changed
1517
+ * files via `gh api` (`commits/<sha>/pulls`, `pulls/<n>/files`), verdicts and
1518
+ * task text from the store at `storeRoot`.
1519
+ *
1520
+ * @param storeRoot - Project root holding the task store.
1521
+ * @param gh - One read-only `gh api` GET, null on failure; defaults to `gh api`.
1522
+ * @returns The lookups.
1523
+ * @task T14696
1524
+ */
1525
+ export function defaultFlakeFixProof(storeRoot, gh = ghApi) {
1526
+ /** Every changed path of a PR, or null when a page cannot be read. */
1527
+ const changedFiles = (prNumber, cwd) => {
1528
+ const files = [];
1529
+ for (let page = 1; page <= PR_FILES_MAX_PAGES; page++) {
1530
+ const rows = gh(`repos/{owner}/{repo}/pulls/${prNumber}/files?per_page=100&page=${page}`, cwd);
1531
+ if (!Array.isArray(rows))
1532
+ return null;
1533
+ for (const row of rows)
1534
+ if (typeof row.filename === 'string')
1535
+ files.push(row.filename);
1536
+ if (rows.length < 100)
1537
+ return files;
1538
+ }
1539
+ return files;
1540
+ };
1541
+ return {
1542
+ async listMergedPrsAt(shas, cwd) {
1543
+ const prs = [];
1544
+ for (const sha of shas) {
1545
+ const pulls = gh(`repos/{owner}/{repo}/commits/${sha}/pulls`, cwd);
1546
+ if (!Array.isArray(pulls))
1547
+ return null;
1548
+ for (const p of pulls) {
1549
+ const head = p.head;
1550
+ if (p.merge_commit_sha !== sha || typeof p.merged_at !== 'string')
1551
+ continue;
1552
+ if (typeof p.number !== 'number' || typeof head?.sha !== 'string')
1553
+ continue;
1554
+ const files = changedFiles(p.number, cwd);
1555
+ if (files === null)
1556
+ return null;
1557
+ prs.push({
1558
+ number: p.number,
1559
+ mergeCommitSha: sha,
1560
+ headSha: head.sha,
1561
+ title: typeof p.title === 'string' ? p.title : '',
1562
+ body: typeof p.body === 'string' ? p.body : '',
1563
+ files,
1564
+ });
1565
+ }
1566
+ }
1567
+ return prs;
1568
+ },
1569
+ async verdictBackedTask(taskId, pr, acs) {
1570
+ const { unverifiedCriteria } = await import('../tasks/merge-close.js');
1571
+ const { currentAcTexts, reviewVerdictsFor } = await import('../tasks/review-verdict.js');
1572
+ const { getTaskAccessor } = await import('../store/data-accessor.js');
1573
+ const task = await (await getTaskAccessor(storeRoot)).loadSingleTask(taskId);
1574
+ if (!task)
1575
+ return null;
1576
+ const verdicts = await reviewVerdictsFor(storeRoot, taskId, pr.number);
1577
+ const gaps = await unverifiedCriteria(verdicts, acs, pr.headSha, await currentAcTexts(storeRoot, taskId));
1578
+ if (gaps.length > 0)
1579
+ return null;
1580
+ const criteria = (task.acceptance ?? []).map((ac) => typeof ac === 'string' ? ac : ac.description);
1581
+ const reasons = verdicts
1582
+ .filter((v) => v.verdict === 'met' && v.headSha === pr.headSha && acs.includes(v.ac))
1583
+ .map((v) => v.reason);
1584
+ return [task.description ?? '', ...criteria, ...reasons].join('\n');
1585
+ },
1586
+ };
1587
+ }
1322
1588
  /**
1323
1589
  * Whether a later commit's CI failed before any test ran (T13809): every
1324
1590
  * failing job's log is readable and failed in a setup action step
@@ -1374,8 +1640,11 @@ function ciDefinitionPaths(required, pins) {
1374
1640
  * The stand-in's CI tested the DESCENDANT's tree, not the merge tree. It is
1375
1641
  * accepted only when that difference cannot matter to the PR:
1376
1642
  * - the merge commit must be superseded, not failed ({@link supersededOnMerge}),
1377
- * unless its failures were inherited from main ({@link inheritedOnMerge}) or
1378
- * were only the flaky-quarantine budget ({@link nonTestFailuresOn}, T13809);
1643
+ * unless its failures were inherited from main ({@link inheritedOnMerge}),
1644
+ * were only the flaky-quarantine budget ({@link nonTestFailuresOn}, T13809),
1645
+ * or were tests a later merged PR proved flaky and fixed
1646
+ * ({@link proveFlakeFixes}, T14696): then only a candidate that includes
1647
+ * every proving PR and passed the same test files stands in;
1379
1648
  * - the PR's own final head (`prHeadSha`) must have a green latest
1380
1649
  * `pull_request` run for every superseded check — a later fix on main
1381
1650
  * never rescues a broken PR;
@@ -1459,6 +1728,26 @@ export async function findGreenDescendant(input) {
1459
1728
  };
1460
1729
  }
1461
1730
  }
1731
+ let flakeFixed;
1732
+ if (!superseded.ok && input.fetchJobLog && input.flakeFixProof) {
1733
+ // T14696: every failing test may be a flake that a later merged PR,
1734
+ // verified by a non-author reviewer, named and fixed.
1735
+ const failing = await failingTestsOn(input.checks, merge, required, pins, input.fetchJobLog, cwd);
1736
+ if (failing.ok) {
1737
+ const later = (input.listDescendants(merge, input.ref, cwd) ?? []).filter((sha) => sha !== merge && input.isAncestor(merge, sha, cwd));
1738
+ const proved = await proveFlakeFixes(failing.tests, later, input.flakeFixProof, cwd);
1739
+ if (proved.ok) {
1740
+ flakeFixed = proved.fixes;
1741
+ superseded = { ok: true, names: unproven() };
1742
+ }
1743
+ else {
1744
+ superseded = {
1745
+ ok: false,
1746
+ reason: `${superseded.reason}; not a proven flake: ${proved.reason}`,
1747
+ };
1748
+ }
1749
+ }
1750
+ }
1462
1751
  if (!superseded.ok)
1463
1752
  return superseded;
1464
1753
  const supersededNames = superseded.names;
@@ -1498,7 +1787,8 @@ export async function findGreenDescendant(input) {
1498
1787
  ...(nonTest ? { nonTest } : {}),
1499
1788
  ...(untested ? { untested } : {}),
1500
1789
  };
1501
- const refuse = (reason) => ({ ok: false, reason, cleared });
1790
+ // T14696: a flake fix closes only through a stand-in that passed the fixed files.
1791
+ const refuse = (reason) => flakeFixed ? { ok: false, reason } : { ok: false, reason, cleared };
1502
1792
  const candidates = input.listDescendants(merge, input.ref, cwd);
1503
1793
  if (candidates === null) {
1504
1794
  return refuse(`cannot list commits on ${input.ref} after ${merge.slice(0, 12)}`);
@@ -1514,6 +1804,9 @@ export async function findGreenDescendant(input) {
1514
1804
  for (const sha of candidates.slice(0, CI_DESCENDANT_MAX_CANDIDATES)) {
1515
1805
  if (sha === merge || !input.isAncestor(merge, sha, cwd))
1516
1806
  continue;
1807
+ // T14696: a run before a proving PR merged never tested its fix.
1808
+ if (flakeFixed?.some((f) => f.proofMergeSha !== sha && !input.isAncestor(f.proofMergeSha, sha, cwd)))
1809
+ continue;
1517
1810
  const range = `${merge.slice(0, 12)}..${sha.slice(0, 12)}`;
1518
1811
  for (const [what, paths] of guarded) {
1519
1812
  const touching = input.touchingCommits(merge, sha, paths, cwd);
@@ -1586,6 +1879,14 @@ export async function findGreenDescendant(input) {
1586
1879
  }
1587
1880
  if (!verdict.ok)
1588
1881
  return refuse(verdict.reason);
1882
+ if (flakeFixed && input.fetchJobLog) {
1883
+ const notShown = await flakeFixNotShown(fetched.checks, sha, flakeFixed, scope, input.fetchJobLog, cwd);
1884
+ // T14696: a run that skipped the job or the file decides nothing; look on.
1885
+ if (notShown !== null) {
1886
+ lastUndecided ??= `${sha.slice(0, 12)}: ${notShown}`;
1887
+ continue;
1888
+ }
1889
+ }
1589
1890
  return {
1590
1891
  ok: true,
1591
1892
  sha,
@@ -1595,8 +1896,8 @@ export async function findGreenDescendant(input) {
1595
1896
  ...(inherited ? { inherited } : {}),
1596
1897
  ...(nonTest ? { nonTest } : {}),
1597
1898
  ...(untested ? { untested } : {}),
1899
+ ...(flakeFixed ? { flakeFixed } : { cleared }),
1598
1900
  ...(passedOver.length > 0 ? { passedOver } : {}),
1599
- cleared,
1600
1901
  };
1601
1902
  }
1602
1903
  return refuse(`no later ${input.ref} commit (first ${CI_DESCENDANT_MAX_CANDIDATES} within 7 days) has a completed push run of ${supersededNames.join(', ')}` +
@@ -2749,6 +3050,7 @@ export async function resolveCiEvidenceAtom(prNumber, roots, opts = {}) {
2749
3050
  firstParentOf: opts.firstParentOf ?? defaultFirstParentOf,
2750
3051
  fetchJobLog: opts.fetchJobLog ?? defaultFetchJobLog,
2751
3052
  fetchJobAnnotations: opts.fetchJobAnnotations ?? defaultFetchJobAnnotations,
3053
+ flakeFixProof: opts.flakeFixProof ?? defaultFlakeFixProof(roots.storeRoot),
2752
3054
  nextMainCommitAt: opts.nextMainCommitAt ?? defaultNextMainCommitAt,
2753
3055
  });
2754
3056
  if (found.ok) {
@@ -2758,7 +3060,7 @@ export async function resolveCiEvidenceAtom(prNumber, roots, opts = {}) {
2758
3060
  ...(head && !mainOnly ? { prHeadSha: head } : {}),
2759
3061
  pins,
2760
3062
  descendantSha: found.sha,
2761
- ...(found.inherited || found.nonTest || found.untested
3063
+ ...(found.inherited || found.nonTest || found.untested || found.flakeFixed
2762
3064
  ? { inheritedFailures: true }
2763
3065
  : {}),
2764
3066
  });
@@ -2772,6 +3074,7 @@ export async function resolveCiEvidenceAtom(prNumber, roots, opts = {}) {
2772
3074
  ...(found.inherited ? { inherited: found.inherited } : {}),
2773
3075
  ...(found.nonTest ? { nonTest: found.nonTest } : {}),
2774
3076
  ...(found.untested ? { untested: found.untested } : {}),
3077
+ ...(found.flakeFixed ? { flakeFixed: found.flakeFixed } : {}),
2775
3078
  ...(found.passedOver ? { passedOver: found.passedOver } : {}),
2776
3079
  };
2777
3080
  }
@@ -3083,6 +3386,20 @@ export async function resolveCiEvidenceAtom(prNumber, roots, opts = {}) {
3083
3386
  ...(descendant.inherited ? { inheritedFailures: descendant.inherited } : {}),
3084
3387
  ...(descendant.nonTest ? { nonTestFailures: descendant.nonTest } : {}),
3085
3388
  ...(descendant.untested ? { untestedFailures: descendant.untested } : {}),
3389
+ ...(descendant.flakeFixed
3390
+ ? {
3391
+ flakeFixedFailures: descendant.flakeFixed.map((f) => ({
3392
+ name: f.job,
3393
+ mergeRunId: f.mergeRunId,
3394
+ ...(f.project ? { project: f.project } : {}),
3395
+ file: f.file,
3396
+ test: f.title,
3397
+ proofPr: f.proofPr,
3398
+ proofTask: f.proofTask,
3399
+ proofMergeSha: f.proofMergeSha,
3400
+ })),
3401
+ }
3402
+ : {}),
3086
3403
  ...(descendant.passedOver ? { passedOverRuns: descendant.passedOver } : {}),
3087
3404
  }
3088
3405
  : {}),