mo3ta-coverage 1.0.18 → 1.0.20

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.
package/AGENT.md ADDED
@@ -0,0 +1,139 @@
1
+ # AGENT.md
2
+
3
+ Guidance for coding agents working in this repository.
4
+
5
+ ## What this project is
6
+
7
+ `mo3ta-coverage` is a Node.js CLI (published to npm) that:
8
+
9
+ 1. Finds source files changed on the current branch vs a base branch.
10
+ 2. Finds the test files related to those changed files.
11
+ 3. Runs Jest only for those tests (or lets Jest expand them).
12
+ 4. Parses `coverage/lcov.info` and checks coverage of the changed lines.
13
+
14
+ The primary use case is CI on pull requests: fail only when changed lines are not
15
+ covered enough, without running the entire test suite.
16
+
17
+ ## Tech stack
18
+
19
+ - Node.js ESM (`"type": "module"`), no build step required for normal use.
20
+ - `commander` for the CLI.
21
+ - Jest 30 for this project's own tests.
22
+ - Babel (`@babel/preset-env`) only to transform JS for Jest.
23
+ - Runtime code lives in `index.js` and `src/`; `dist/` is not committed.
24
+
25
+ ## Commands
26
+
27
+ ```bash
28
+ npm install
29
+ npm test # jest --coverage
30
+
31
+ # Basic CLI run from another project
32
+ node /path/to/mo3ta-coverage/index.js --mode smart --base origin/main --limit 80
33
+
34
+ # This repository's CLI options
35
+ node index.js --help
36
+ ```
37
+
38
+ There is no lint/typecheck/format script. `npm run build` currently outputs
39
+ `dist/index.js` from `index.js` only; it is not part of the normal workflow.
40
+
41
+ ## Repository layout
42
+
43
+ | Path | Purpose |
44
+ | --- | --- |
45
+ | `index.js` | CLI entry point: option parsing, config file read/write, calls `main()`. |
46
+ | `src/cli.js` | Orchestration: changed files, test selection, Jest invocation, lcov reporting. |
47
+ | `src/fileUtils.js` | File classification and changed-file → test-file mapping. |
48
+ | `src/gitUtils.js` | Git repo/base-branch validation. |
49
+ | `src/cli.test.js` | Tests for lcov parsing, changed-line classification, summaries. |
50
+ | `src/fileUtils.test.js` | Tests for file filtering, naming conventions, import scanning. |
51
+ | `jest.config.json` | Jest config: `**/src/**/*.test.js`, node env, babel-jest transform. |
52
+ | `.mo3ta-coverage.json` | Optional per-project config (gitignored here). |
53
+
54
+ ## Execution flow
55
+
56
+ ```text
57
+ index.js
58
+ └─ main(options) src/cli.js
59
+ ├─ verifyGitRepoExists() src/gitUtils.js
60
+ ├─ getChangedFiles(base) git log/diff/diff --cached, sort -u
61
+ ├─ runRelatedTests(files, mode, depth)
62
+ │ └─ npx jest ... --coverage
63
+ └─ reportUncoveredChangedLines(...)
64
+ ├─ parseLcov(path)
65
+ ├─ getChangedLines(file, base) git diff -U0
66
+ ├─ classifyChangedLineCoverage(...)
67
+ └─ exit 1 when overall coverage < limit
68
+ ```
69
+
70
+ ### Changed-file detection
71
+
72
+ `getChangedFiles()` unions:
73
+
74
+ - files from commits authored by the current git user between
75
+ `merge-base HEAD <base>` and `HEAD`,
76
+ - unstaged changes,
77
+ - staged changes.
78
+
79
+ It keeps only `.js/.ts/.jsx/.tsx` and drops `node_modules`, `coverage`, `dist`,
80
+ `build`, and `.git` paths. Paths are relative to `process.cwd()`.
81
+
82
+ ### Modes
83
+
84
+ - `fast`: naming-convention matches only (plus changed test files), with the
85
+ existing direct import-scan fallback. No dependency traversal.
86
+ - `smart` (default): naming-convention matches **plus** a reverse-dependency
87
+ search over the import graph, limited by `--depth` (default `2`). This finds
88
+ spec files whose names do not match the source file and tests that reach the
89
+ changed file through one intermediate module (for example a barrel
90
+ `index.js`).
91
+ - `full`: passes the changed source and test files to
92
+ `jest --findRelatedTests`, letting Jest do unbounded traversal.
93
+
94
+ Depth semantics for `smart`: one edge = an import. `--depth 1` finds test files
95
+ that import the changed file directly. `--depth 2` also finds test files that
96
+ import a module which imports the changed file.
97
+
98
+ ### Coverage reporting
99
+
100
+ - `parseLcov()` absolutizes `SF:` paths.
101
+ - Changed lines are the added line numbers from `git diff -U0 <base> -- <file>`.
102
+ - Only lines present in lcov (`DA:`) are counted; imports/comments are ignored.
103
+ - The overall ratio is computed across all changed, coverable lines.
104
+ - A missing lcov file exits with code 1; below-limit coverage exits with code 1.
105
+ - `main()` wraps everything and exits 1 on unexpected errors.
106
+
107
+ ## Conventions
108
+
109
+ - Use ESM `import`/`export`; no CommonJS in `src/`.
110
+ - Keep functions small, pure where possible, and exported only when tested.
111
+ - File-path logic uses `fs`/`path` and must work with both relative git paths and
112
+ absolute lcov paths.
113
+ - Walkers skip `node_modules`, `.git`, `dist`, `build`, `coverage`, `.next`,
114
+ `.turbo`, and dot-directories (`SKIP_DIRS` plus the dot-prefix check).
115
+ - Import parsing is regex-based (`IMPORT_SPECIFIER_RE`), intentionally
116
+ dependency-free. It handles `import`, `export ... from`, `require`, dynamic
117
+ `import()`, and `jest.mock()`.
118
+ - Test files are recognized by `(\.test|\.spec)\.(js|ts|jsx|tsx)$`.
119
+ - New behavior in `src/fileUtils.js` or `src/cli.js` should come with tests in
120
+ the matching `*.test.js` file.
121
+ - Do not add runtime dependencies without a clear need; the package ships only
122
+ `commander`.
123
+
124
+ ## Gotchas
125
+
126
+ - `findTestFilesForSource` and `findRelatedTestFilesBySource` return paths
127
+ relative to the scan root; `findTestFilesByImport` also accepts a `root` for
128
+ tests using temp fixtures.
129
+ - Import-graph and test-file scans are cached per root for the lifetime of the
130
+ process. Tests must use a fresh temp directory per fixture (they do).
131
+ - Alias resolution is heuristic: `@/` and `~/` are stripped, then the specifier
132
+ is matched against repo-relative paths by exact match or path suffix.
133
+ Over-matching is acceptable (it may run extra tests) but under-matching is not.
134
+ - `runRelatedTests` exits the process (`exit(0)`/`exit(1)`) rather than throwing.
135
+ - The config subcommand writes `.mo3ta-coverage.json` in `process.cwd()`.
136
+ - CLI options with commander defaults (`mode`, `depth`) override config unless
137
+ you check `program.getOptionValueSource(...) === 'cli'`.
138
+ - Shell commands are built as strings and run with `execSync`; quote/escape file
139
+ paths if this ever needs to support spaces.
package/README.md CHANGED
@@ -5,8 +5,9 @@ mo3ta-coverage checks coverage for changed lines in a pull request. It finds cha
5
5
  ## Features
6
6
 
7
7
  - Detects changed JS/TS files from git history and working tree
8
- - Maps changed source files to nearby test files automatically
8
+ - Maps changed source files to related test files, even when names differ
9
9
  - Supports three execution modes: `fast`, `smart`, and `full`
10
+ - Walks reverse imports in `smart` mode to a configurable depth (default `2`)
10
11
  - Parses `lcov.info` and reports uncovered changed lines
11
12
  - Enforces a minimum coverage threshold for changed lines
12
13
 
@@ -31,12 +32,23 @@ mo3ta-coverage --mode smart --base origin/main --limit 80
31
32
  | `--limit <percent>` | Minimum changed-line coverage percentage | `80` |
32
33
  | `--showCovered <bool>` | Show covered changed lines in output | `false` |
33
34
  | `--mode <mode>` | Execution mode: `fast`, `smart`, or `full` | `smart` |
35
+ | `--depth <number>` | Max reverse-import depth used by `smart` (`1` or `2` recommended) | `2` |
34
36
 
35
37
  ## Modes
36
38
 
37
- - `fast`: Direct execution of mapped test files only. No Jest dependency traversal.
38
- - `smart`: Direct execution of changed test files only. It does not expand to mapped or imported test files, and performs no Jest dependency traversal.
39
- - `full`: Runs mapped test files through `jest --findRelatedTests`.
39
+ - `fast`: Naming-convention matches only, plus a direct import-scan fallback. No dependency traversal.
40
+ - `smart`: Naming-convention matches plus a reverse-import walk from each changed file, limited by `--depth`. This finds spec files whose names differ and tests that reach the changed file through intermediate modules such as barrel `index.js` files. No Jest dependency traversal.
41
+ - `full`: Passes the changed source and test files to `jest --findRelatedTests`, letting Jest traverse without a depth limit.
42
+
43
+ ### Depth in `smart` mode
44
+
45
+ One depth step is one import edge:
46
+
47
+ - `--depth 1`: test files that import the changed file directly.
48
+ - `--depth 2` (default): also test files that import a module which imports the changed file.
49
+
50
+ Depth `2` is usually the sweet spot: it catches barrel/re-export and thin wrapper
51
+ layers without pulling in the whole dependency graph.
40
52
 
41
53
  ## Recommended Mode
42
54
 
@@ -53,7 +65,7 @@ Use `full` only when you intentionally want Jest to expand to related tests.
53
65
  You can persist defaults with the `config` subcommand:
54
66
 
55
67
  ```sh
56
- mo3ta-coverage config --base origin/main --mode smart
68
+ mo3ta-coverage config --base origin/main --mode smart --depth 2
57
69
  ```
58
70
 
59
71
  This writes `.mo3ta-coverage.json` in the project root.
@@ -62,7 +74,9 @@ This writes `.mo3ta-coverage.json` in the project root.
62
74
 
63
75
  1. Reads CLI options and saved config from [index.js](index.js).
64
76
  2. Finds changed source files from git in [src/cli.js](src/cli.js).
65
- 3. Maps source files to nearby test files in [src/fileUtils.js](src/fileUtils.js).
77
+ 3. Maps source files to related test files in [src/fileUtils.js](src/fileUtils.js).
78
+ `smart` mode combines naming conventions with a cached reverse-import index
79
+ and walks it up to `--depth` edges.
66
80
  4. Runs Jest in the selected mode from [src/cli.js](src/cli.js).
67
81
  5. Parses `lcov.info` and reports uncovered changed lines.
68
82
 
@@ -10,15 +10,29 @@ mo3ta-coverage --mode smart --base origin/main --limit 80
10
10
 
11
11
  ## Why `smart`
12
12
 
13
- `smart` avoids Jest dependency traversal by running only test files that are themselves changed in the diff. It never expands to every test file related to a changed source file, which keeps the run predictable for large projects.
13
+ `smart` avoids Jest dependency traversal by running only the related test files directly. It combines naming-convention matches with a depth-limited reverse-import walk: test files that directly import a changed file (`--depth 1`), or that import a module which imports it (`--depth 2`, the default). That catches differently named specs and barrel/re-export layers without pulling in the whole dependency graph, making it the most predictable mode for large projects.
14
14
 
15
15
  ## Mode Comparison
16
16
 
17
17
  | Mode | What Jest Receives | Traversal | Typical Outcome |
18
18
  |------|--------------------|-----------|-----------------|
19
- | `fast` | mapped test files | none | fastest run |
20
- | `smart` | changed test files only | none | predictable changed-file check |
21
- | `full` | mapped test files via `--findRelatedTests` | yes | can expand widely |
19
+ | `fast` | naming-mapped test files (+ direct import fallback) | none | fastest run |
20
+ | `smart` | related test files (naming + reverse imports, depth ≤ 2) | bounded | best balance |
21
+ | `full` | changed source/test files via `--findRelatedTests` | unbounded | can expand widely |
22
+
23
+ ## Tuning `smart` Depth
24
+
25
+ ```bash
26
+ # Direct importers only
27
+ mo3ta-coverage --mode smart --depth 1
28
+
29
+ # Direct importers plus one intermediate module (default)
30
+ mo3ta-coverage --mode smart --depth 2
31
+ ```
32
+
33
+ Use `--depth 1` when modules are tested directly. Keep `--depth 2` when the
34
+ codebase uses barrel `index.js` files or thin wrapper modules between a helper
35
+ and its spec.
22
36
 
23
37
  ## Project Setup
24
38
 
@@ -33,7 +47,8 @@ mo3ta-coverage --mode smart --base origin/main --limit 80
33
47
  ```json
34
48
  {
35
49
  "base": "origin/main",
36
- "mode": "smart"
50
+ "mode": "smart",
51
+ "depth": 2
37
52
  }
38
53
  ```
39
54
 
package/index.js CHANGED
@@ -35,6 +35,7 @@ program
35
35
  .option('--limit <percent>', 'Minimum required coverage percentage for all changed lines (e.g., 80)', '80')
36
36
  .option('--showCovered <bool>', 'Show covered changed lines in the output', false)
37
37
  .option('--mode <mode>', 'Execution mode: fast, smart, or full', 'smart')
38
+ .option('--depth <number>', 'Smart mode max reverse-dependency depth (1 = direct importers, 2 = also importers of importers)', '2')
38
39
  .enablePositionalOptions(); // used to allow using same options in subcommands
39
40
 
40
41
 
@@ -43,6 +44,7 @@ program
43
44
  .description('Set or get configuration options')
44
45
  .option('--base <branch>', 'Set default base branch')
45
46
  .option('--mode <mode>', 'Set default mode (fast/smart/full)')
47
+ .option('--depth <number>', 'Set default smart-mode depth (1-10)')
46
48
  .action((opts) => {
47
49
  let config = readConfig();
48
50
 
@@ -66,6 +68,17 @@ program
66
68
  updated = true;
67
69
  console.log(`Default mode set to: ${config.mode}`);
68
70
  }
71
+
72
+ if (opts.depth !== undefined) {
73
+ const normalizedDepth = Number.parseInt(opts.depth, 10);
74
+ if (!Number.isInteger(normalizedDepth) || normalizedDepth < 1 || normalizedDepth > 10) {
75
+ console.error(`Invalid depth: ${opts.depth}. Expected an integer between 1 and 10.`);
76
+ process.exit(1);
77
+ }
78
+ config.depth = normalizedDepth;
79
+ updated = true;
80
+ console.log(`Default smart-mode depth set to: ${config.depth}`);
81
+ }
69
82
  if (updated) {
70
83
  writeConfig(config);
71
84
  } else {
@@ -79,6 +92,9 @@ program
79
92
  program.action((opts) => {
80
93
  const config = readConfig();
81
94
  const options = program.opts();
95
+
96
+ const modeFromCli = program.getOptionValueSource('mode') === 'cli';
97
+ const depthFromCli = program.getOptionValueSource('depth') === 'cli';
82
98
 
83
99
  // Use config base if not provided in CLI
84
100
  if (!options.base && config.base) {
@@ -87,7 +103,7 @@ program.action((opts) => {
87
103
  options.base = 'origin/main';
88
104
  }
89
105
 
90
- if (!options.mode && config.mode) {
106
+ if (!modeFromCli && config.mode) {
91
107
  options.mode = config.mode;
92
108
  }
93
109
 
@@ -97,6 +113,19 @@ program.action((opts) => {
97
113
  process.exit(1);
98
114
  }
99
115
 
116
+ if (options.mode === 'smart') {
117
+ if (!depthFromCli && config.depth !== undefined) {
118
+ options.depth = String(config.depth);
119
+ }
120
+
121
+ const depth = Number.parseInt(options.depth, 10);
122
+ if (!Number.isInteger(depth) || depth < 1 || depth > 10) {
123
+ console.error(`Invalid depth: ${options.depth}. Expected an integer between 1 and 10.`);
124
+ process.exit(1);
125
+ }
126
+ options.depth = depth;
127
+ }
128
+
100
129
  console.log(`Final options: ${JSON.stringify(options, null, 2)}`);
101
130
 
102
131
  main(options);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "mo3ta-coverage",
3
- "version": "1.0.18",
3
+ "version": "1.0.20",
4
4
  "description": "Run tests and report uncovered changed lines in a PR",
5
5
  "main": "index.js",
6
6
  "bin": {
package/src/cli.js CHANGED
@@ -3,7 +3,13 @@ import fs from 'fs';
3
3
  import path from 'path';
4
4
  import { exit } from 'process';
5
5
  import { verifyBaseBranchExists, verifyGitRepoExists } from './gitUtils.js';
6
- import { getJsOnlyFiles, separateSourceAndTestFiles, findTestFilesForSource, findTestFilesByImport } from './fileUtils.js';
6
+ import {
7
+ getJsOnlyFiles,
8
+ separateSourceAndTestFiles,
9
+ findTestFilesForSource,
10
+ findTestFilesByImport,
11
+ findRelatedTestFilesBySource
12
+ } from './fileUtils.js';
7
13
 
8
14
  export function main(options) {
9
15
  try {
@@ -15,11 +21,12 @@ export function main(options) {
15
21
  const COVERAGE_LIMIT = parseFloat(options.limit);
16
22
  const SHOW_COVERED = options.showCovered === true || options.showCovered === 'true';
17
23
  const MODE = options.mode;
24
+ const DEPTH = Number.parseInt(options.depth, 10) || 2;
18
25
 
19
- console.log(`Options:\nBase Branch: ${BASE_BRANCH} \nLCOV Path: ${LCOV_PATH} \nCoverage Limit: ${COVERAGE_LIMIT} \nShow Covered Lines: ${SHOW_COVERED} \nMode: ${MODE}`);
26
+ console.log(`Options:\nBase Branch: ${BASE_BRANCH} \nLCOV Path: ${LCOV_PATH} \nCoverage Limit: ${COVERAGE_LIMIT} \nShow Covered Lines: ${SHOW_COVERED} \nMode: ${MODE} \nDepth: ${DEPTH}`);
20
27
 
21
28
  const changedFiles = getChangedFiles(BASE_BRANCH);
22
- runRelatedTests(changedFiles, MODE);
29
+ runRelatedTests(changedFiles, MODE, DEPTH);
23
30
  reportUncoveredChangedLines(changedFiles, LCOV_PATH, BASE_BRANCH, COVERAGE_LIMIT, SHOW_COVERED);
24
31
  } catch (error) {
25
32
  console.error('❌ An unexpected error occurred:', error.message || error);
@@ -53,15 +60,18 @@ function getChangedFiles(BASE_BRANCH) {
53
60
  }
54
61
  }
55
62
 
56
- export function selectTestFilesForMode(mode, changedTestFiles, mappedTestFiles) {
57
- if (mode === 'smart') {
58
- return changedTestFiles;
59
- }
63
+ function runJest(command) {
64
+ console.log(` Jest command: ${command}`);
60
65
 
61
- return mappedTestFiles;
66
+ try {
67
+ execSync(command, { stdio: 'inherit' });
68
+ } catch (err) {
69
+ console.error('❌ Tests failed:', err.message || err);
70
+ exit(1);
71
+ }
62
72
  }
63
73
 
64
- function runRelatedTests(files, mode) {
74
+ function runRelatedTests(files, mode, depth = 2) {
65
75
  if (files.length === 0) {
66
76
  console.log('✅ No changed source files found.');
67
77
  exit(0);
@@ -84,32 +94,51 @@ function runRelatedTests(files, mode) {
84
94
  testFiles.forEach(file => console.log(` - ${file}`));
85
95
  }
86
96
 
87
- // Find test files for changed source files
97
+ // Full mode delegates discovery to Jest, so pass the changed files themselves.
98
+ if (mode === 'full') {
99
+ const jestTargets = [...sourceFiles, ...testFiles];
100
+
101
+ if (jestTargets.length === 0) {
102
+ console.log('\n⚠️ No changed source or test files found to run.');
103
+ exit(0);
104
+ }
105
+
106
+ console.log(`\n📝 Test strategy: full (Jest --findRelatedTests, unbounded traversal)`);
107
+ console.log(` Running tests related to ${sourceFiles.length} source file(s) + ${testFiles.length} changed test(s)`);
108
+ console.log(` ⚠️ If this expands to too many tests, switch to --mode smart`);
109
+ console.log(' Files passed to Jest:');
110
+ jestTargets.forEach(file => console.log(` - ${file}`));
111
+
112
+ runJest(`npx jest --findRelatedTests --passWithNoTests --coverage ${jestTargets.join(' ')}`);
113
+ return;
114
+ }
115
+
116
+ // Fast: naming-convention mapping with a direct-import fallback.
117
+ // Smart: naming-convention mapping plus a depth-limited reverse-dependency walk.
88
118
  const testFilesToRun = new Set(testFiles);
89
- const mappedTests = new Map(); // Track which tests map to which source files
90
119
 
91
120
  sourceFiles.forEach(sourceFile => {
92
- let relatedTests = findTestFilesForSource(sourceFile);
93
- let matchType = 'naming convention';
94
-
95
- // Fallback: spec files don't have to follow the same-name convention.
96
- // If no name-based test file exists, look for test files that import this source file.
97
- if (relatedTests.length === 0) {
98
- relatedTests = findTestFilesByImport(sourceFile);
99
- if (relatedTests.length > 0) {
100
- matchType = 'import scan';
121
+ let relatedTests;
122
+ let matchType;
123
+
124
+ if (mode === 'smart') {
125
+ relatedTests = findRelatedTestFilesBySource(sourceFile, { maxDepth: depth });
126
+ matchType = `naming + import graph, depth ≤ ${depth}`;
127
+ } else {
128
+ relatedTests = findTestFilesForSource(sourceFile);
129
+ matchType = 'naming convention';
130
+
131
+ if (relatedTests.length === 0) {
132
+ relatedTests = findTestFilesByImport(sourceFile);
133
+ if (relatedTests.length > 0) {
134
+ matchType = 'import scan';
135
+ }
101
136
  }
102
137
  }
103
138
 
104
139
  if (relatedTests.length > 0) {
105
140
  console.log(` ✓ ${sourceFile} → ${relatedTests.length} test file(s) (${matchType})`);
106
- relatedTests.forEach(test => {
107
- testFilesToRun.add(test);
108
- if (!mappedTests.has(test)) {
109
- mappedTests.set(test, []);
110
- }
111
- mappedTests.get(test).push(sourceFile);
112
- });
141
+ relatedTests.forEach(test => testFilesToRun.add(test));
113
142
  } else {
114
143
  console.log(` ⚠ ${sourceFile} → No test file found`);
115
144
  }
@@ -124,65 +153,20 @@ function runRelatedTests(files, mode) {
124
153
  }
125
154
 
126
155
  console.log(`\n🧪 Running ${finalTestFiles.length} test file(s):\n`, finalTestFiles.join('\n'));
156
+ console.log(' Files passed to Jest:');
157
+ finalTestFiles.forEach(file => console.log(` - ${file}`));
127
158
 
128
- if (mode === 'fast') {
129
- console.log(`\n📝 Test strategy: fast (Direct execution, no Jest dependency traversal)`);
159
+ if (mode === 'smart') {
160
+ console.log(`\n📝 Test strategy: smart (naming + reverse imports, depth ≤ ${depth})`);
130
161
  console.log(` Test files: ${finalTestFiles.length}`);
131
- console.log(` Source files detected: ${sourceFiles.length}`);
132
- console.log(' Files passed to Jest:');
133
- finalTestFiles.forEach(file => console.log(` - ${file}`));
134
- const command = `npx jest --passWithNoTests --coverage ${finalTestFiles.join(' ')}`;
135
- console.log(` Jest command: ${command}`);
136
-
137
- try {
138
- execSync(command, { stdio: 'inherit' });
139
- } catch (err) {
140
- console.error('❌ Tests failed:', err.message || err);
141
- exit(1);
142
- }
143
- } else if (mode === 'smart') {
144
- // Smart mode is intentionally scoped to the changed files in the diff.
145
- // Mapped tests can include unchanged files (especially when a source file
146
- // is imported by a broad test suite), which makes smart mode unexpectedly
147
- // run the whole suite. Only changed test files belong in this mode.
148
- const changedTestFiles = selectTestFilesForMode(mode, testFiles, finalTestFiles);
149
- if (changedTestFiles.length === 0) {
150
- console.log('\n⚠️ No changed test files found to run in smart mode.');
151
- console.log('Change a test file or use --mode full to run related tests for changed source files.');
152
- exit(0);
153
- }
154
-
155
- console.log(`\n📝 Test strategy: smart (Run only changed test files, no Jest dependency traversal)`);
156
- console.log(` Test files: ${changedTestFiles.length}`);
157
162
  console.log(` Source files for coverage: ${sourceFiles.length}`);
158
- console.log(' Files passed to Jest:');
159
- changedTestFiles.forEach(file => console.log(` - ${file}`));
160
- const command = `npx jest --passWithNoTests --coverage ${changedTestFiles.join(' ')}`;
161
- console.log(` Jest command: ${command}`);
162
-
163
- try {
164
- execSync(command, { stdio: 'inherit' });
165
- } catch (err) {
166
- console.error('❌ Tests failed:', err.message || err);
167
- exit(1);
168
- }
169
163
  } else {
170
- console.log(`\n📝 Test strategy: full (Run mapped tests through Jest --findRelatedTests)`);
171
- console.log(` Running tests for ${sourceFiles.length} source file(s) + ${testFiles.length} changed test(s)`);
172
- console.log(` Test files in Jest command: ${finalTestFiles.length}`);
173
- console.log(` ⚠️ If this expands to too many tests, switch to --mode smart`);
174
- console.log(' Test files passed to Jest:');
175
- finalTestFiles.forEach(file => console.log(` - ${file}`));
176
- const command = `npx jest --findRelatedTests --passWithNoTests --coverage ${finalTestFiles.join(' ')}`;
177
- console.log(` Jest command: ${command}`);
178
-
179
- try {
180
- execSync(command, { stdio: 'inherit' });
181
- } catch (err) {
182
- console.error('❌ Tests failed:', err.message || err);
183
- exit(1);
184
- }
164
+ console.log(`\n📝 Test strategy: fast (Direct execution, no Jest dependency traversal)`);
165
+ console.log(` Test files: ${finalTestFiles.length}`);
166
+ console.log(` Source files detected: ${sourceFiles.length}`);
185
167
  }
168
+
169
+ runJest(`npx jest --passWithNoTests --coverage ${finalTestFiles.join(' ')}`);
186
170
  }
187
171
 
188
172
  function getChangedLines(filePath, BASE_BRANCH) {
package/src/cli.test.js CHANGED
@@ -5,7 +5,6 @@ import {
5
5
  classifyChangedLineCoverage,
6
6
  formatMissedLinesSummary,
7
7
  parseLcov,
8
- selectTestFilesForMode,
9
8
  summarizeCoverageResult
10
9
  } from './cli.js';
11
10
 
@@ -92,20 +91,6 @@ describe('summarizeCoverageResult', () => {
92
91
  });
93
92
  });
94
93
 
95
- describe('selectTestFilesForMode', () => {
96
- const changedTests = ['src/changed.test.js'];
97
- const mappedTests = ['src/changed.test.js', 'src/unchanged.test.js'];
98
-
99
- it('limits smart mode to test files changed in the diff', () => {
100
- expect(selectTestFilesForMode('smart', changedTests, mappedTests)).toEqual(changedTests);
101
- });
102
-
103
- it('keeps mapped tests for non-smart modes', () => {
104
- expect(selectTestFilesForMode('fast', changedTests, mappedTests)).toEqual(mappedTests);
105
- expect(selectTestFilesForMode('full', changedTests, mappedTests)).toEqual(mappedTests);
106
- });
107
- });
108
-
109
94
  describe('formatMissedLinesSummary', () => {
110
95
  it('formats uncovered files and lines for the final summary', () => {
111
96
  const result = formatMissedLinesSummary([
package/src/fileUtils.js CHANGED
@@ -57,16 +57,16 @@ export function separateSourceAndTestFiles(files) {
57
57
  }
58
58
 
59
59
  /**
60
- * Finds potential test files for a given source file
61
- * Checks multiple naming conventions and locations
62
- * @param {string} sourceFile - Path to source file
63
- * @returns {string[]} - Array of potential test file paths
60
+ * Builds candidate test paths for a source file using common naming conventions.
61
+ * Paths are relative and have not been checked against the filesystem.
62
+ * @param {string} sourceFile - Path to source file (relative)
63
+ * @returns {string[]} - Candidate test file paths
64
64
  */
65
- export function findTestFilesForSource(sourceFile) {
65
+ function getTestFileCandidates(sourceFile) {
66
66
  const testFiles = [];
67
67
  const parsed = path.parse(sourceFile);
68
68
  const extensions = ['.js', '.ts', '.jsx', '.tsx'];
69
-
69
+
70
70
  // Pattern 1: Same directory with .test or .spec suffix
71
71
  // e.g., src/utils/helper.js → src/utils/helper.test.js
72
72
  extensions.forEach(ext => {
@@ -89,15 +89,36 @@ export function findTestFilesForSource(sourceFile) {
89
89
  const baseDir = srcMatch[1];
90
90
  const relativePath = srcMatch[2];
91
91
  const relParsed = path.parse(relativePath);
92
-
92
+
93
93
  extensions.forEach(ext => {
94
94
  testFiles.push(path.join(baseDir, 'tests', relParsed.dir, `${relParsed.name}.test${ext}`));
95
95
  testFiles.push(path.join(baseDir, 'tests', relParsed.dir, `${relParsed.name}.spec${ext}`));
96
96
  });
97
97
  }
98
98
 
99
- // Check which test files actually exist
100
- return testFiles.filter(testFile => fs.existsSync(testFile));
99
+ return testFiles;
100
+ }
101
+
102
+ /**
103
+ * Finds potential test files for a given source file
104
+ * Checks multiple naming conventions and locations
105
+ * @param {string} sourceFile - Path to source file
106
+ * @returns {string[]} - Array of potential test file paths
107
+ */
108
+ export function findTestFilesForSource(sourceFile) {
109
+ return getTestFileCandidates(sourceFile).filter(testFile => fs.existsSync(testFile));
110
+ }
111
+
112
+ /**
113
+ * Root-aware variant of findTestFilesForSource used by the import graph walker.
114
+ * Existence is checked relative to `root`, while returned paths stay relative.
115
+ * @param {string} sourceFile - Path to source file relative to root
116
+ * @param {string} root - Directory the paths are relative to
117
+ * @returns {string[]} - Existing test file paths relative to root
118
+ */
119
+ function findTestFilesForSourceInRoot(sourceFile, root) {
120
+ return getTestFileCandidates(sourceFile)
121
+ .filter(testFile => fs.existsSync(path.resolve(root, testFile)));
101
122
  }
102
123
 
103
124
  let cachedAllTestFiles = null;
@@ -235,3 +256,214 @@ export function findTestFilesByImport(sourceFile, root = process.cwd()) {
235
256
 
236
257
  return matching;
237
258
  }
259
+
260
+ let cachedAllJsFiles = null;
261
+
262
+ /**
263
+ * Collects every JS/TS file under the given root, skipping dependency/build
264
+ * directories. Results are cached per root for the lifetime of the CLI run.
265
+ * @param {string} [root] - Directory to scan (defaults to cwd)
266
+ * @returns {string[]} - File paths relative to root
267
+ */
268
+ export function findAllJsFiles(root = process.cwd()) {
269
+ if (cachedAllJsFiles && cachedAllJsFiles.root === root) {
270
+ return cachedAllJsFiles.files;
271
+ }
272
+
273
+ const results = [];
274
+ const walk = dir => {
275
+ let entries;
276
+ try {
277
+ entries = fs.readdirSync(dir, { withFileTypes: true });
278
+ } catch {
279
+ return;
280
+ }
281
+ entries.forEach(entry => {
282
+ const fullPath = path.join(dir, entry.name);
283
+ if (entry.isDirectory()) {
284
+ if (!SKIP_DIRS.has(entry.name) && !entry.name.startsWith('.')) {
285
+ walk(fullPath);
286
+ }
287
+ } else if (JS_EXTENSIONS.some(ext => entry.name.endsWith(ext))) {
288
+ results.push(path.relative(root, fullPath));
289
+ }
290
+ });
291
+ };
292
+
293
+ walk(root);
294
+ cachedAllJsFiles = { root, files: results };
295
+ return results;
296
+ }
297
+
298
+ function isTestFile(filePath) {
299
+ return TEST_FILE_RE.test(filePath);
300
+ }
301
+
302
+ function stripJsExtension(filePath) {
303
+ return filePath.replace(/\.(js|ts|jsx|tsx|mjs|cjs)$/, '');
304
+ }
305
+
306
+ /**
307
+ * Builds a lookup of repo-relative paths without extensions. Multiple files can
308
+ * share a path stem when they use different extensions (e.g. helper.js/.ts).
309
+ */
310
+ function buildNoExtIndex(files) {
311
+ const index = new Map();
312
+ files.forEach(file => {
313
+ const key = stripJsExtension(file);
314
+ if (!index.has(key)) index.set(key, []);
315
+ index.get(key).push(file);
316
+ });
317
+ return index;
318
+ }
319
+
320
+ /**
321
+ * Resolves a non-relative (alias or package-style) specifier to files under
322
+ * root. Heuristics, in order:
323
+ * 1. exact repo-relative stem match ('src/utils/helper'),
324
+ * 2. path-suffix match ('utils/helper' → 'src/utils/helper').
325
+ * '@/x' and '~/x' aliases are normalized before matching.
326
+ */
327
+ function resolveNonRelativeSpecifier(specifier, root, noExtIndex) {
328
+ let stem = stripJsExtension(specifier);
329
+ if (stem.startsWith('@/') || stem.startsWith('~/')) {
330
+ stem = stem.slice(2);
331
+ }
332
+ if (!stem) return [];
333
+
334
+ const exact = noExtIndex.get(stem);
335
+ if (exact) {
336
+ return exact.map(file => path.resolve(root, file));
337
+ }
338
+
339
+ const suffix = `/${stem}`;
340
+ const matches = [];
341
+ for (const [key, files] of noExtIndex) {
342
+ if (key.endsWith(suffix)) {
343
+ files.forEach(file => matches.push(path.resolve(root, file)));
344
+ }
345
+ }
346
+ return matches;
347
+ }
348
+
349
+ /**
350
+ * Resolves an import specifier found in `fromFile` to absolute file paths.
351
+ * Relative specifiers resolve against the importing file's directory; alias
352
+ * and package-style specifiers resolve against the repo-relative file index.
353
+ */
354
+ function resolveImportTargets(specifier, fromFile, root, noExtIndex) {
355
+ if (specifier.startsWith('.')) {
356
+ const fromDir = path.dirname(path.resolve(root, fromFile));
357
+ return resolveSpecifierCandidates(specifier, fromDir);
358
+ }
359
+ return resolveNonRelativeSpecifier(specifier, root, noExtIndex);
360
+ }
361
+
362
+ let cachedReverseImportIndex = null;
363
+
364
+ /**
365
+ * Builds (and caches per root) a reverse import index:
366
+ * absolute module path → Set of absolute paths that import it.
367
+ * All JS/TS files participate, so traversal can pass through intermediate
368
+ * modules such as barrel files.
369
+ * @param {string} [root] - Directory to scan (defaults to cwd)
370
+ * @returns {Map<string, Set<string>>}
371
+ */
372
+ export function buildReverseImportIndex(root = process.cwd()) {
373
+ if (cachedReverseImportIndex && cachedReverseImportIndex.root === root) {
374
+ return cachedReverseImportIndex.index;
375
+ }
376
+
377
+ const files = findAllJsFiles(root);
378
+ const noExtIndex = buildNoExtIndex(files);
379
+ const index = new Map();
380
+
381
+ files.forEach(relFile => {
382
+ let content;
383
+ try {
384
+ content = fs.readFileSync(path.resolve(root, relFile), 'utf8');
385
+ } catch {
386
+ return;
387
+ }
388
+
389
+ const importerPath = path.resolve(root, relFile);
390
+ extractImportSpecifiers(content).forEach(specifier => {
391
+ resolveImportTargets(specifier, relFile, root, noExtIndex).forEach(target => {
392
+ if (!index.has(target)) index.set(target, new Set());
393
+ index.get(target).add(importerPath);
394
+ });
395
+ });
396
+ });
397
+
398
+ cachedReverseImportIndex = { root, index };
399
+ return index;
400
+ }
401
+
402
+ /**
403
+ * Finds test files related to one source file. Combines:
404
+ * 1. naming-convention matches, and
405
+ * 2. a reverse-dependency walk through the import graph, limited to
406
+ * `maxDepth` edges from the source file.
407
+ *
408
+ * Depth 1 = test imports the source directly.
409
+ * Depth 2 = test imports a module that imports the source (e.g. a barrel).
410
+ *
411
+ * @param {string} sourceFile - Path to source file (relative to root)
412
+ * @param {{root?: string, maxDepth?: number}} [options]
413
+ * @returns {string[]} - Related test file paths relative to root, sorted
414
+ */
415
+ export function findRelatedTestFilesBySource(sourceFile, {
416
+ root = process.cwd(),
417
+ maxDepth = 2
418
+ } = {}) {
419
+ const related = new Set(findTestFilesForSourceInRoot(sourceFile, root));
420
+ const depthLimit = Math.max(0, Number.parseInt(maxDepth, 10) || 0);
421
+ if (depthLimit === 0) {
422
+ return Array.from(related).sort();
423
+ }
424
+
425
+ const reverseIndex = buildReverseImportIndex(root);
426
+ const start = path.resolve(root, sourceFile);
427
+ const visited = new Set([start]);
428
+ let frontier = new Set([start]);
429
+
430
+ for (let depth = 1; depth <= depthLimit && frontier.size > 0; depth++) {
431
+ const next = new Set();
432
+
433
+ frontier.forEach(node => {
434
+ const importers = reverseIndex.get(node);
435
+ if (!importers) return;
436
+
437
+ importers.forEach(importer => {
438
+ if (visited.has(importer)) return;
439
+ visited.add(importer);
440
+
441
+ const relImporter = path.relative(root, importer);
442
+ if (isTestFile(relImporter)) {
443
+ related.add(relImporter);
444
+ } else {
445
+ // Non-test importers are only useful as traversal hops.
446
+ next.add(importer);
447
+ }
448
+ });
449
+ });
450
+
451
+ frontier = next;
452
+ }
453
+
454
+ return Array.from(related).sort();
455
+ }
456
+
457
+ /**
458
+ * Finds test files related to any of the given source files.
459
+ * @param {string[]} sourceFiles - Source paths relative to root
460
+ * @param {{root?: string, maxDepth?: number}} [options]
461
+ * @returns {string[]} - Sorted, de-duplicated related test paths
462
+ */
463
+ export function findRelatedTestFiles(sourceFiles, options = {}) {
464
+ const related = new Set();
465
+ sourceFiles.forEach(sourceFile => {
466
+ findRelatedTestFilesBySource(sourceFile, options).forEach(testFile => related.add(testFile));
467
+ });
468
+ return Array.from(related).sort();
469
+ }
@@ -1,4 +1,10 @@
1
- import { getJsOnlyFiles, separateSourceAndTestFiles, findTestFilesForSource, findTestFilesByImport } from './fileUtils';
1
+ import {
2
+ getJsOnlyFiles,
3
+ separateSourceAndTestFiles,
4
+ findTestFilesForSource,
5
+ findTestFilesByImport,
6
+ findRelatedTestFilesBySource
7
+ } from './fileUtils';
2
8
  import fs from 'fs';
3
9
  import os from 'os';
4
10
  import path from 'path';
@@ -319,3 +325,94 @@ describe('findTestFilesByImport', () => {
319
325
  expect(result).toEqual(['src/real.test.js']);
320
326
  });
321
327
  });
328
+
329
+ describe('findRelatedTestFilesBySource', () => {
330
+ let tempDir;
331
+
332
+ function createFixture(structure) {
333
+ tempDir = fs.mkdtempSync(path.join(os.tmpdir(), 'mo3ta-related-'));
334
+ Object.entries(structure).forEach(([filePath, content]) => {
335
+ const absolutePath = path.join(tempDir, filePath);
336
+ fs.mkdirSync(path.dirname(absolutePath), { recursive: true });
337
+ fs.writeFileSync(absolutePath, content);
338
+ });
339
+ return tempDir;
340
+ }
341
+
342
+ afterEach(() => {
343
+ fs.rmSync(tempDir, { recursive: true, force: true });
344
+ });
345
+
346
+ it('includes same-name test files and differently named importer specs', () => {
347
+ const root = createFixture({
348
+ 'src/widget.js': 'export const widget = 1;',
349
+ 'src/widget.test.js': "import { widget } from './widget';\n",
350
+ 'src/integration.spec.js': "import { widget } from './widget';\n"
351
+ });
352
+
353
+ const result = findRelatedTestFilesBySource('src/widget.js', { root });
354
+
355
+ expect(result).toEqual(['src/integration.spec.js', 'src/widget.test.js']);
356
+ });
357
+
358
+ it('finds a direct importer at depth 1', () => {
359
+ const root = createFixture({
360
+ 'lib/helper.js': 'export const add = (a, b) => a + b;',
361
+ 'lib/custom-name.spec.js': "import { add } from './helper';\n"
362
+ });
363
+
364
+ const result = findRelatedTestFilesBySource('lib/helper.js', { root, maxDepth: 1 });
365
+
366
+ expect(result).toEqual(['lib/custom-name.spec.js']);
367
+ });
368
+
369
+ it('finds a spec that reaches the source through one intermediate module at depth 2', () => {
370
+ const root = createFixture({
371
+ 'lib/helper.js': 'export const add = (a, b) => a + b;',
372
+ 'lib/service.js': "import { add } from './helper';\nexport const run = () => add(1, 2);\n",
373
+ 'lib/feature.spec.js': "import { run } from './service';\n"
374
+ });
375
+
376
+ const depthOne = findRelatedTestFilesBySource('lib/helper.js', { root, maxDepth: 1 });
377
+ const depthTwo = findRelatedTestFilesBySource('lib/helper.js', { root, maxDepth: 2 });
378
+
379
+ expect(depthOne).toEqual([]);
380
+ expect(depthTwo).toEqual(['lib/feature.spec.js']);
381
+ });
382
+
383
+ it('finds specs that import the source through a barrel index', () => {
384
+ const root = createFixture({
385
+ 'src/utils/helper.js': 'export const add = (a, b) => a + b;',
386
+ 'src/utils/index.js': "export * from './helper';\n",
387
+ 'src/app.test.js': "import { add } from './utils';\n"
388
+ });
389
+
390
+ const result = findRelatedTestFilesBySource('src/utils/helper.js', { root, maxDepth: 2 });
391
+
392
+ expect(result).toEqual(['src/app.test.js']);
393
+ });
394
+
395
+ it('resolves alias imports while walking the graph', () => {
396
+ const root = createFixture({
397
+ 'src/utils/helper.js': 'export const add = (a, b) => a + b;',
398
+ 'src/services/user.js': "import { add } from '@/utils/helper';\nexport const total = () => add(1, 1);\n",
399
+ 'src/user.spec.js': "import { total } from './services/user';\n"
400
+ });
401
+
402
+ const result = findRelatedTestFilesBySource('src/utils/helper.js', { root, maxDepth: 2 });
403
+
404
+ expect(result).toEqual(['src/user.spec.js']);
405
+ });
406
+
407
+ it('does not return unrelated test files', () => {
408
+ const root = createFixture({
409
+ 'src/utils/helper.js': 'export const add = (a, b) => a + b;',
410
+ 'src/unrelated.test.js': "import { other } from './other';\n",
411
+ 'src/other.js': 'export const other = 1;'
412
+ });
413
+
414
+ const result = findRelatedTestFilesBySource('src/utils/helper.js', { root, maxDepth: 2 });
415
+
416
+ expect(result).toEqual([]);
417
+ });
418
+ });