From 2a1e3e3c4ca4caf491f5f76153276336c5e9f89e Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 21 Nov 2026 00:41:30 +0000 Subject: [PATCH 1/2] ci(tests): run Vitest for the base baseline as well as head The base job ran Jest, whose config only matches *.test.js and has no TypeScript transform, so no .ts suite ever reached the baseline. The compare script treats a file missing from the base report as zero failures, so every pre-existing .ts failure on main showed up as new, even on docs-only PRs. No suite uses jest.mock/jest.fn any more, so run Vitest on both targets. Also fix format detection in compare-jest-failures.cjs: Vitest's JSON report carries numFailedTests too, so it was labelled [jest]. Use the Jest-only top-level keys instead. Add an optional --base-files list (git ls-files at base, uploaded by the base job). A failing head file that exists at base but is missing from the base report is now reported as "not comparable" rather than new; files added by the PR still count as new. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01CADHZgpqByUXMSV8M5d5HQ --- .github/workflows/tests.yml | 35 ++++--- scripts/validation/compare-jest-failures.cjs | 87 +++++++++++----- .../validation/compare-jest-failures.test.js | 98 ++++++++++++++++++- 3 files changed, 181 insertions(+), 39 deletions(-) diff --git a/.github/workflows/tests.yml b/.github/workflows/tests.yml index 8e6c2765..bf97f3c8 100644 --- a/.github/workflows/tests.yml +++ b/.github/workflows/tests.yml @@ -1,7 +1,7 @@ name: Tests # Runs the Vitest suite on every PR and fails only on failures the PR -# introduces: develop still carries known failures (#3472), so the head and +# introduces: main may still carry known failures (#3472), so the head and # base are tested in parallel and compared. Once #3472 clears the baseline, # this can gate on zero failures instead (#3479). @@ -95,23 +95,15 @@ jobs: - name: Install dependencies run: npm ci --ignore-scripts --prefer-offline --no-audit --no-fund - - name: Run tests (Jest on base, Vitest on head during cutover) + - name: Run Vitest env: EVENT_NAME: ${{ github.event_name }} - TARGET: ${{ matrix.target }} run: | - # During Jest-to-Vitest cutover: base contains jest.mock() calls, - # head contains vi.* mocks. Use Jest baseline to ensure head comparison - # is valid. Once base catches up, simplify to Vitest everywhere. + # Head and base both run Vitest so the compare job diffs like with + # like. Jest only matched *.test.js, so a Jest baseline never ran + # the .ts suites and every head .ts failure looked new. test_status=0 - - if [ "$TARGET" = "base" ]; then - # Base revision still has jest.mock() — must run Jest - npx jest --config jest.config.js --ci --json --outputFile=jest-report.json || test_status=$? - else - # Head revision has vi.* mocks — run Vitest - npx vitest run --reporter=json --outputFile=jest-report.json --coverage=false || test_status=$? - fi + npx vitest run --reporter=json --outputFile=jest-report.json --coverage=false || test_status=$? # Report summary and detect empty suites num_suites=$(jq '.numTotalTestSuites // (.testResults | length)' jest-report.json 2>/dev/null || echo 0) @@ -141,11 +133,19 @@ jobs: printf '%s\n' "$dirty" fi + - name: List files tracked at base + if: matrix.target == 'base' + # Lets the compare job tell a test file the PR adds (new) from one + # that existed at base but is missing from its report (not comparable). + run: git ls-files > base-files.txt + - name: Upload report uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 with: name: vitest-report-${{ matrix.target }} - path: jest-report.json + path: | + jest-report.json + base-files.txt if-no-files-found: ignore retention-days: 7 @@ -190,10 +190,15 @@ jobs: # makes their test paths comparable. The default shell is # bash -e: suspend errexit so a non-zero result still reaches the # summary below. + base_files_args=() + if [ -s reports/vitest-report-base/base-files.txt ]; then + base_files_args=(--base-files reports/vitest-report-base/base-files.txt) + fi set +e node scripts/validation/compare-jest-failures.cjs \ --head reports/vitest-report-head/jest-report.json --head-root "$GITHUB_WORKSPACE" \ --base reports/vitest-report-base/jest-report.json --base-root "$GITHUB_WORKSPACE" \ + "${base_files_args[@]}" \ | tee comparison.txt status=${PIPESTATUS[0]} set -e diff --git a/scripts/validation/compare-jest-failures.cjs b/scripts/validation/compare-jest-failures.cjs index 0235cfc4..5b229b5f 100644 --- a/scripts/validation/compare-jest-failures.cjs +++ b/scripts/validation/compare-jest-failures.cjs @@ -5,13 +5,19 @@ * * Supports both Jest and Vitest JSON output formats. Compares test failure * counts between the PR head and base branch to detect if the PR introduces - * new test failures. Known failures on develop don't block the PR, only NEW + * new test failures. Known failures on main don't block the PR, only NEW * failures introduced by the PR are reported. * * Usage: * node compare-jest-failures.cjs \ * --head --head-root \ - * --base --base-root + * --base --base-root \ + * [--base-files ] + * + * When --base-files is given, a failing head file that is missing from the + * base report but tracked at the base commit is reported as "not comparable" + * rather than "new": base never ran it, so there is no baseline. A file the + * PR adds is not tracked at base and still counts as new. */ const fs = require('fs'); @@ -26,7 +32,7 @@ for (let i = 0; i < args.length; i += 2) { } if (!opts.head || !opts.base || !['head-root', 'base-root'].every(k => opts[k])) { - console.error('Usage: node compare-jest-failures.cjs --head --head-root --base --base-root '); + console.error('Usage: node compare-jest-failures.cjs --head --head-root --base --base-root [--base-files ]'); process.exit(1); } @@ -42,31 +48,49 @@ function readReport(filePath) { } // Detect report format: Jest vs Vitest +// +// Vitest's JSON reporter mirrors Jest's top-level counters (including +// numFailedTests), so those cannot tell the formats apart. Jest alone emits +// numRuntimeErrorTestSuites, wasInterrupted and openHandles at the top level, +// and per-file numFailingTests in its legacy output. function detectFormat(report) { if (!report || !Array.isArray(report.testResults)) { return null; } - // Both formats have testResults array, but field names differ slightly - // Vitest uses 'assertionResults' for individual test results - // Jest uses 'numFailingTests' prominently but also 'assertionResults' - - // Check first result to infer format (heuristic) - const firstResult = report.testResults[0]; - if (!firstResult) return 'unknown'; - - // Both use assertionResults, so check other fields - if (firstResult.numFailingTests !== undefined || report.numFailedTests !== undefined) { + const jestOnlyKeys = ['numRuntimeErrorTestSuites', 'wasInterrupted', 'openHandles']; + if (jestOnlyKeys.some(key => key in report)) { + return 'jest'; + } + if (report.testResults.some(result => result && result.numFailingTests !== undefined)) { return 'jest'; } - // Vitest typically has 'duration' and other fields - if (firstResult.duration !== undefined) { - return 'vitest'; + return 'vitest'; +} + +// List every test file in a report, normalised relative to root +function listFiles(report, root) { + if (!report || !Array.isArray(report.testResults)) { + return new Set(); } + return new Set(report.testResults.map(result => path.relative(root || '.', result.name))); +} - // Default to jest for compatibility - return 'jest'; +// Read the optional list of files tracked at the base commit (one per line, +// relative to the repository root, as printed by `git ls-files`) +function readFileList(filePath) { + if (!filePath) { + return null; + } + try { + return new Set( + fs.readFileSync(filePath, 'utf8').split('\n').map(line => line.trim()).filter(Boolean), + ); + } catch (error) { + console.error(`Failed to read base file list ${filePath}: ${error.message}`); + process.exit(1); + } } // Count failures by test file, normalized relative to root @@ -130,15 +154,24 @@ const baseFormat = detectFormat(baseReport); const headFailures = countFailures(headReport, opts['head-root']); const baseFailures = countFailures(baseReport, opts['base-root']); -// Calculate per-file comparison: count new failures (head > base) -const newFailuresByFile = Object.entries(headFailures).reduce((acc, [file, count]) => { +const baseReportFiles = listFiles(baseReport, opts['base-root']); +const baseTrackedFiles = readFileList(opts['base-files']); + +// Calculate per-file comparison: count new failures (head > base). A file +// that base never reported cannot be compared if it already existed there. +const newFailuresByFile = {}; +const notComparableByFile = {}; +Object.entries(headFailures).forEach(([file, count]) => { + if (!baseReportFiles.has(file) && baseTrackedFiles && baseTrackedFiles.has(file)) { + notComparableByFile[file] = count; + return; + } const baseCount = baseFailures[file] || 0; const newCount = Math.max(0, count - baseCount); if (newCount > 0) { - acc[file] = { head: count, base: baseCount, new: newCount }; + newFailuresByFile[file] = { head: count, base: baseCount, new: newCount }; } - return acc; -}, {}); +}); const headTotal = Object.values(headFailures).reduce((a, b) => a + b, 0); const baseTotal = Object.values(baseFailures).reduce((a, b) => a + b, 0); @@ -148,6 +181,14 @@ console.log(`Base branch failures: ${baseTotal} (${Object.keys(baseFailures).len console.log(`PR head failures: ${headTotal} (${Object.keys(headFailures).length} files) [${headFormat}]`); console.log(`New failures in this PR: ${totalNewFailures}`); +const notComparable = Object.entries(notComparableByFile); +if (notComparable.length > 0) { + console.log(`\n⚠️ ${notComparable.length} failing file(s) not comparable (exist at base but missing from the base report):`); + notComparable.forEach(([file, count]) => { + console.log(` • ${file}: ${count} failure(s) on head`); + }); +} + if (totalNewFailures > 0) { console.error(`\n❌ This PR introduces ${totalNewFailures} new test failure(s):`); Object.entries(newFailuresByFile).forEach(([file, data]) => { diff --git a/scripts/validation/compare-jest-failures.test.js b/scripts/validation/compare-jest-failures.test.js index 90f588f1..0c3dec9a 100644 --- a/scripts/validation/compare-jest-failures.test.js +++ b/scripts/validation/compare-jest-failures.test.js @@ -21,9 +21,12 @@ afterEach(() => { * and optional statuses and assertion results. * @param {Array} baseFiles - Base suite fixtures in the same format. * @param {boolean} [rawCounts=false] - Use numeric failure counts instead of assertion results. + * @param {Object} [options] - Extra fixture options. + * @param {Object} [options.topLevel] - Extra top-level report fields per target ({ head, base }). + * @param {Array} [options.baseTracked] - Files tracked at base, passed as --base-files. * @returns {import('node:child_process').SpawnSyncReturns} CLI output and exit status. */ -function compare(headFiles, baseFiles, rawCounts = false) { +function compare(headFiles, baseFiles, rawCounts = false, options = {}) { const roots = { head: path.join(fixtureRoot, 'head'), base: path.join(fixtureRoot, 'base'), @@ -31,6 +34,7 @@ function compare(headFiles, baseFiles, rawCounts = false) { Object.entries({ head: headFiles, base: baseFiles }).forEach(([target, files]) => { const report = { + ...(options.topLevel?.[target] || {}), numFailedTests: files.reduce((total, file) => total + file.failures, 0), testResults: files.map(file => { const result = { @@ -53,12 +57,20 @@ function compare(headFiles, baseFiles, rawCounts = false) { writeFileSync(path.join(fixtureRoot, `${target}.json`), JSON.stringify(report)); }); + const extraArgs = []; + if (options.baseTracked) { + const listPath = path.join(fixtureRoot, 'base-files.txt'); + writeFileSync(listPath, `${options.baseTracked.join('\n')}\n`); + extraArgs.push('--base-files', listPath); + } + return spawnSync(process.execPath, [ script, '--head', path.join(fixtureRoot, 'head.json'), '--head-root', roots.head, '--base', path.join(fixtureRoot, 'base.json'), '--base-root', roots.base, + ...extraArgs, ], { encoding: 'utf8' }); } @@ -184,3 +196,87 @@ test('also compares reports containing per-file numeric failure counts', () => { expect(result.status).toBe(1); expect(result.stdout).toContain('New failures in this PR: 2'); }); + +describe('report format detection', () => { + const jestTopLevel = { numRuntimeErrorTestSuites: 0, wasInterrupted: false, openHandles: [] }; + + test('labels Vitest reports as vitest even though they carry numFailedTests', () => { + const files = [{ name: 'tests/existing.test.ts', failures: 1 }]; + const result = compare(files, files); + + expect(result.stdout).toMatch(/Base branch failures: .*\[vitest\]/); + expect(result.stdout).toMatch(/PR head failures: .*\[vitest\]/); + }); + + test('labels reports with Jest-only top-level fields as jest', () => { + const files = [{ name: 'tests/existing.test.js', failures: 1 }]; + const result = compare(files, files, false, { topLevel: { base: jestTopLevel } }); + + expect(result.stdout).toMatch(/Base branch failures: .*\[jest\]/); + expect(result.stdout).toMatch(/PR head failures: .*\[vitest\]/); + }); + + test('labels legacy per-file numFailingTests reports as jest', () => { + const files = [{ name: 'tests/existing.test.js', failures: 1 }]; + const result = compare(files, files, true); + + expect(result.stdout).toMatch(/PR head failures: .*\[jest\]/); + }); +}); + +describe('--base-files', () => { + test('reports a failing file that existed at base but is missing from its report as not comparable', () => { + const result = compare( + [{ name: 'tests/existing.test.ts', failures: 2 }], + [{ name: 'tests/other.test.ts', failures: 0 }], + false, + { baseTracked: ['tests/existing.test.ts', 'tests/other.test.ts'] }, + ); + + expect(result.status).toBe(0); + expect(result.stdout).toContain('New failures in this PR: 0'); + expect(result.stdout).toContain('not comparable'); + expect(result.stdout).toContain('tests/existing.test.ts: 2 failure(s) on head'); + }); + + test('still counts a failing file added by the PR as new', () => { + const result = compare( + [{ name: 'tests/added.test.ts', failures: 1 }], + [], + false, + { baseTracked: ['tests/existing.test.ts'] }, + ); + + expect(result.status).toBe(1); + expect(result.stdout).toContain('New failures in this PR: 1'); + expect(result.stdout).not.toContain('not comparable'); + }); + + test('still compares a file that base reported as passing', () => { + const result = compare( + [{ name: 'tests/existing.test.ts', failures: 1 }], + [{ name: 'tests/existing.test.ts', failures: 0 }], + false, + { baseTracked: ['tests/existing.test.ts'] }, + ); + + expect(result.status).toBe(1); + expect(result.stdout).toContain('New failures in this PR: 1'); + }); + + test('fails when the base file list cannot be read', () => { + const files = [{ name: 'tests/existing.test.ts', failures: 0 }]; + compare(files, files); + const result = spawnSync(process.execPath, [ + script, + '--head', path.join(fixtureRoot, 'head.json'), + '--head-root', path.join(fixtureRoot, 'head'), + '--base', path.join(fixtureRoot, 'base.json'), + '--base-root', path.join(fixtureRoot, 'base'), + '--base-files', path.join(fixtureRoot, 'missing.txt'), + ], { encoding: 'utf8' }); + + expect(result.status).toBe(1); + expect(result.stderr).toContain('Failed to read base file list'); + }); +}); From 1c8bbcbddd3fdd7098ff795e58263be42de5f27d Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 21 Nov 2026 00:42:49 +0000 Subject: [PATCH 2/2] docs(changelog): note Vitest baseline fix for tests CI Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01CADHZgpqByUXMSV8M5d5HQ --- CHANGELOG.md | 1 + 1 file changed, 1 insertion(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 98c13cc9..351860c7 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -36,6 +36,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Fixed +- **Tests CI reported pre-existing failures as new** — the "No new test failures" comparison ran Jest for the base commit, which never ran TypeScript suites, so every failing `.ts` suite on head looked new (even on docs-only PRs). Both head and base now run Vitest; the comparison script labels Vitest reports correctly and reports a failing file that existed at base but is missing from the base report as "not comparable" rather than new. - **Reader access verification never succeeded** — the code request emailed one code but stored the hash of a different one; the stored hash now derives from the emailed code, and comparison is constant-time. - **Reader access endpoints crashed at runtime** — restored the verification-code and recovery storage functions removed from `store.ts`, and handled the real Netlify Blobs `list()` result shape so session creation no longer throws. - **Reader API routing** — `/api/reader/code-requests` and `/api/reader/verifications` now reach their functions; `/api/reader/chapters/{id}` routes to the session-validated chapter endpoint, and chapter content reads the `sessionToken` cookie the app actually sets.