mo3ta-coverage 1.3.0 → 1.3.3

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 CHANGED
@@ -61,9 +61,9 @@ index.js
61
61
  ├─ verifyGitRepoExists() src/gitUtils.js
62
62
  ├─ getExplicitFiles(options) --files / --filesFrom, or
63
63
  ├─ getChangedFiles(base) merge-base diff + working tree, all authors
64
- ├─ dryRun(files, mode, depth) --dryRun: print the would-run test list, exit 0
65
- ├─ runRelatedTests(files, mode, depth)
66
- │ └─ npx jest ... --coverage
64
+ ├─ dryRun(files, mode, depth, filter) --dryRun: print the would-run (filtered) test list, exit 0
65
+ ├─ runRelatedTests(files, mode, depth, jestFlags)
66
+ │ └─ npx jest ... --coverage [--jest flags]
67
67
  └─ reportUncoveredChangedLines(...)
68
68
  ├─ parseLcov(path)
69
69
  ├─ getChangedLines(file, base) git diff -U0
@@ -103,6 +103,19 @@ Depth semantics for `smart`: one edge = an import. `--depth 1` finds test files
103
103
  that import the changed file directly. `--depth 2` also finds test files that
104
104
  import a module which imports the changed file.
105
105
 
106
+ ### Spec filter
107
+
108
+ `--filter <regex>` (CLI, config `"filter"`, or the API/MCP `filter` argument)
109
+ compiles to a regex via `parseFilter()` and is applied to the **final** list
110
+ of selected spec paths by `filterTestFiles()` inside `resolveTestPlan()`.
111
+ `resolveTestPlan` returns both `allTestsToRun` (before the filter) and
112
+ `testsToRun` (after it); `logFilteredTestFiles()` prints both lists so the
113
+ user can validate the regex. An invalid regex throws
114
+ `INVALID_FILTER`, which `main()` turns into exit 1. In `full` mode the regex
115
+ is also appended to Jest's args as `--testPathPatterns` (skipped when the
116
+ caller already supplied a Jest path pattern via `--jest`). Config values are
117
+ merged in `index.js` before `main()`.
118
+
106
119
  ### Coverage reporting
107
120
 
108
121
  - `parseLcov()` absolutizes `SF:` paths.
@@ -143,8 +156,17 @@ import a module which imports the changed file.
143
156
  is matched against repo-relative paths by exact match or path suffix.
144
157
  Over-matching is acceptable (it may run extra tests) but under-matching is not.
145
158
  - `runRelatedTests` exits the process (`exit(0)`/`exit(1)`) rather than throwing.
159
+ - Extra Jest flags come from `--jest` (repeatable or comma-separated, parsed by
160
+ `parseJestArgs`) and are appended after the selected test files in
161
+ `resolveTestPlan`. `.mo3ta-coverage.json` can store a `jest` array as a default;
162
+ a CLI `--jest` overrides it. The API/MCP path reads the same `jest` option.
163
+ - The API's captured run (`buildCapturedJestArgs`) adds `--runInBand` for
164
+ timeout control, but drops it when the caller passes `--maxWorkers`/`-w`/`-i`
165
+ because Jest rejects `--runInBand` together with `--maxWorkers`.
146
166
  - `--dryRun` must keep stdout a clean one-path-per-line list (other tools
147
- consume it); informational messages go to stderr.
167
+ consume it); informational messages go to stderr, including the
168
+ before/after filter log (`dryRun` receives the filter and prints the log
169
+ via `console.error`).
148
170
  - The config subcommand writes `.mo3ta-coverage.json` in `process.cwd()`.
149
171
  - CLI options with commander defaults (`mode`, `depth`) override config unless
150
172
  you check `program.getOptionValueSource(...) === 'cli'`.
package/README.md CHANGED
@@ -179,6 +179,8 @@ specs that reach the changed file through barrel files. See
179
179
  | `--depth <number>` | Max reverse-import depth used by `smart` (`1` or `2` recommended) | `2` |
180
180
  | `--files <files...>` | Scan only these files instead of auto-detecting changed files (space- or comma-separated) | – |
181
181
  | `--filesFrom <path>` | Read the file list to scan from a newline-separated file | – |
182
+ | `--jest <value>` | Extra Jest CLI flag passed through to the run, e.g. `--maxWorkers=2`. Repeatable or comma-separated | – |
183
+ | `--filter <regex>` | Regex matched against the final list of selected spec files; only matching test files run. The full and filtered lists are both printed for validation | – |
182
184
  | `--ci <bool>` | CI mode: emit results as a markdown table and save it to a file so CI can read it without parsing logs | `false` |
183
185
  | `--ciReport <path>` | Where to save the CI markdown table | `coverage/mo3ta-coverage-report.md` |
184
186
  | `--dryRun <bool>` | Print the test files that would run (one per line) and stop, without running Jest or the coverage check | `false` |
@@ -205,6 +207,93 @@ Explicitly provided files skip git changed-file detection. Their changed lines
205
207
  are still computed against `--base`, so only lines that differ from the base
206
208
  branch are counted toward coverage.
207
209
 
210
+ ## Passing Extra Jest Flags
211
+
212
+ Use `--jest` to forward any Jest CLI flag to the underlying Jest run, for
213
+ example to control parallelism or silence output. Pass it once per flag, or
214
+ comma-separate several flags in one value:
215
+
216
+ ```sh
217
+ # Limit Jest to 2 workers and run silently
218
+ mo3ta-coverage --base origin/main --jest --maxWorkers=2 --jest --silent
219
+
220
+ # Same thing, comma-separated
221
+ mo3ta-coverage --base origin/main --jest "--maxWorkers=2,--silent"
222
+
223
+ # A single flag that takes a value
224
+ mo3ta-coverage --base origin/main --jest --maxWorkers=50%
225
+ ```
226
+
227
+ The flags are appended to the arguments mo3ta-coverage already passes
228
+ (`--coverage`, `--passWithNoTests`, and the selected test files), so they are
229
+ handled by Jest's own argument parser. Use them for things like `--maxWorkers`,
230
+ `--silent`, `--ci`, `--bail`, `--testTimeout`, or `--coverageDirectory`.
231
+
232
+ Jest flags that take a value work best in the `=` form (`--maxWorkers=2`). If a
233
+ flag's value is normally separated by a space, give each token its own `--jest`:
234
+
235
+ ```sh
236
+ # Equivalent to: jest --maxWorkers 2
237
+ mo3ta-coverage --base origin/main --jest --maxWorkers --jest 2
238
+ ```
239
+
240
+ To make flags the default for a repo, save them with the `config` subcommand:
241
+
242
+ ```sh
243
+ mo3ta-coverage config --jest --maxWorkers=2 --jest --silent
244
+ # written to .mo3ta-coverage.json as "jest": ["--maxWorkers=2", "--silent"]
245
+ ```
246
+
247
+ A `--jest` value on the command line overrides the saved list.
248
+
249
+ ## Filtering Spec Files
250
+
251
+ Pass `--filter` a regular expression. After the mode has selected the test
252
+ files that would run, only the ones that **match** the regex are executed
253
+ (everything else is skipped). The regex is matched against the full
254
+ repo-relative spec path, so it can narrow by directory, project, or name:
255
+
256
+ ```sh
257
+ # Only run specs under the login feature folder
258
+ mo3ta-coverage --base origin/main --filter "src/__tests__/login"
259
+
260
+ # Only run specs whose name contains "auth"
261
+ mo3ta-coverage --base origin/main --filter "auth"
262
+
263
+ # Combined with an explicit file list and a dry run to preview
264
+ mo3ta-coverage --files src/a.js,src/b.ts --base main --dryRun true --filter "b"
265
+ ```
266
+
267
+ For validation, the run logs both lists:
268
+
269
+ ```text
270
+ 🔎 Filter regex: /src\/__tests__\/login/
271
+ All test files before filter (5):
272
+ - src/__tests__/login.spec.js
273
+ - src/checkout/checkout.spec.js
274
+ ...
275
+ Test files after filter (1):
276
+ - src/__tests__/login.spec.js
277
+ ```
278
+
279
+ If the filter matches nothing, no tests are run and the tool exits 0 with
280
+ that log block, so you can see the candidate list and adjust the pattern.
281
+
282
+ In `full` mode the filter is also forwarded to Jest as
283
+ `--testPathPatterns`, since Jest discovers the related specs itself. If you
284
+ already set a Jest path pattern via `--jest --testPathPatterns=...`, your own
285
+ pattern wins.
286
+
287
+ To make the filter the default for a repo, save it with the `config`
288
+ subcommand:
289
+
290
+ ```sh
291
+ mo3ta-coverage config --filter "src/__tests__/login"
292
+ # written to .mo3ta-coverage.json as "filter": "src/__tests__/login"
293
+ ```
294
+
295
+ A `--filter` value on the command line overrides the saved one.
296
+
208
297
  ## CI Mode
209
298
 
210
299
  Pass `--ci true` to print the coverage results as a markdown table **and**
@@ -311,7 +400,12 @@ You can persist defaults with the `config` subcommand:
311
400
  mo3ta-coverage config --base origin/main --mode smart --depth 2
312
401
  ```
313
402
 
314
- This writes `.mo3ta-coverage.json` in the project root.
403
+ This writes `.mo3ta-coverage.json` in the project root. The `base`, `mode`,
404
+ `depth`, `jest` (extra Jest flags), and `filter` (spec filter regex) defaults
405
+ are supported. For example, `mo3ta-coverage config --jest --maxWorkers=2`
406
+ saves a default Jest worker cap, and
407
+ `mo3ta-coverage config --filter "src/__tests__/login"` saves a default spec
408
+ filter.
315
409
 
316
410
  ## MCP server
317
411
 
@@ -319,7 +413,7 @@ This writes `.mo3ta-coverage.json` in the project root.
319
413
 
320
414
  The server is a second bin in this package, `mo3ta-coverage-mcp`, speaking MCP over stdio. It lives here rather than in a separate package so one publish ships it, and so it imports this repo's source directly. The CLI flags, stdout, and exit codes are unchanged; the [GitHub Action](https://github.com/MahmoudMabrok/mo3ta-coverage-action) keeps running `node index.js`.
321
415
 
322
- The server requires Node.js 18 or newer. Each tool takes `root` (the checkout to inspect). When `root` is omitted, Claude Code's `CLAUDE_PROJECT_DIR` is used if it is set, otherwise the server process cwd. `useConfig` defaults to true: `base`, `mode`, and `depth` are read from `.mo3ta-coverage.json` when present, and explicit arguments override the file.
416
+ The server requires Node.js 18 or newer. Each tool takes `root` (the checkout to inspect). When `root` is omitted, Claude Code's `CLAUDE_PROJECT_DIR` is used if it is set, otherwise the server process cwd. `useConfig` defaults to true: `base`, `mode`, `depth`, `jest`, and `filter` are read from `.mo3ta-coverage.json` when present, and explicit arguments override the file.
323
417
 
324
418
  | Tool | Purpose |
325
419
  | --- | --- |
@@ -327,7 +421,9 @@ The server requires Node.js 18 or newer. Each tool takes `root` (the checkout to
327
421
  | `map_related_tests` | Map those files to the tests `fast`, `smart`, or `full` mode would run. |
328
422
  | `check_changed_line_coverage` | Run the changed-line coverage check and return uncovered lines with source text. |
329
423
 
330
- `check_changed_line_coverage` runs the repo's local Jest and writes `coverage/` there, same as the CLI. Jest is killed after `timeoutMs` (default 5 minutes) and only a tail of its output is returned. Pass `runTests: false` to grade an existing `lcov.info` without running tests. A missed threshold comes back as data (`ok: false` plus the uncovered lines), not a crashed tool. A missing git repo, a bad base ref, a missing Jest install, or a timeout comes back as a tool error with a `code` and a hint.
424
+ `check_changed_line_coverage` runs the repo's local Jest and writes `coverage/` there, same as the CLI. Jest is killed after `timeoutMs` (default 5 minutes) and only a tail of its output is returned. Pass `runTests: false` to grade an existing `lcov.info` without running tests. Pass `jest` (an array of flags or a comma-separated string, e.g. `["--maxWorkers=4"]`) to forward extra Jest CLI flags, and `filter` (a regex) to narrow the final list of selected spec files. A missed threshold comes back as data (`ok: false` plus the uncovered lines), not a crashed tool. A missing git repo, a bad base ref, a missing Jest install, or a timeout comes back as a tool error with a `code` and a hint.
425
+
426
+ When a `filter` is used, results include `allTestsToRun` (the selected specs before the filter) and `testsToRun` (what matched), so an agent can validate that the regex kept what it expected.
331
427
 
332
428
  `full` mode still delegates discovery to `jest --findRelatedTests`. `map_related_tests` can only list the changed test files until a check actually runs Jest, matching `--dryRun`.
333
429
 
package/index.js CHANGED
@@ -1,7 +1,7 @@
1
1
  #!/usr/bin/env node
2
2
 
3
3
 
4
- import { Command } from 'commander';
4
+ import { Command, Option } from 'commander';
5
5
  import { main } from './src/cli.js';
6
6
  import fs from 'fs';
7
7
  import path from 'path';
@@ -31,6 +31,14 @@ function writeConfig(config) {
31
31
  console.log(`Updated config: ${JSON.stringify(config, null, 2)}`);
32
32
  }
33
33
 
34
+ // commander accumulator for the repeatable `--jest` option: each occurrence is
35
+ // appended, and a comma within one value splits it into separate flags. The
36
+ // result stays in the order the user typed the flags.
37
+ function collectJest(value, previous) {
38
+ const list = Array.isArray(previous) && previous.length > 0 ? previous : [];
39
+ return list.concat(String(value).split(',').map(flag => flag.trim()).filter(Boolean));
40
+ }
41
+
34
42
  const program = new Command();
35
43
 
36
44
  const PkgPath = new URL('./package.json', import.meta.url);
@@ -52,7 +60,9 @@ program
52
60
  .option('--depth <number>', 'Smart mode max reverse-dependency depth (1 = direct importers, 2 = also importers of importers)', '2')
53
61
  .option('--files <files...>', 'Scan only these files instead of detecting changed files (space- or comma-separated)')
54
62
  .option('--filesFrom <path>', 'Read the list of files to scan from a newline-separated file')
63
+ .addOption(new Option('--jest <value>', 'Extra Jest CLI flag, e.g. --maxWorkers=2 (repeatable or comma-separated)').argParser(collectJest))
55
64
  .option('--dryRun <bool>', 'Print the test files that would run (one per line) and exit, without running Jest or the coverage check', false)
65
+ .option('--filter <regex>', 'Regex matched against the final list of selected spec files; only matching test files run. The full list and the filtered list are both printed so you can validate the filter.')
56
66
  .enablePositionalOptions(); // used to allow using same options in subcommands
57
67
 
58
68
  // Usage help text (printed next to --help)
@@ -65,6 +75,8 @@ $ mo3ta-coverage --filesFrom changed.txt --base origin/main
65
75
  $ mo3ta-coverage --dryRun true --files src/a.js,src/b.ts --base main
66
76
  $ mo3ta-coverage --mode fast --showCovered true
67
77
  $ mo3ta-coverage --mode smart --base origin/main --ci true --ciReport coverage/report.md
78
+ $ mo3ta-coverage --base origin/main --jest --maxWorkers=2 --jest --silent
79
+ $ mo3ta-coverage --base origin/main --filter "src/__tests__/login"
68
80
  $ mo3ta-coverage config --mode smart --depth 2
69
81
  $ mo3ta-coverage --version
70
82
 
@@ -76,12 +88,14 @@ Modes:
76
88
  See README.md for details: https://github.com/MahmoudMabrok/mo3ta-coverage`);
77
89
 
78
90
 
79
- program
91
+ const configCommand = program
80
92
  .command('config')
81
93
  .description('Set or get configuration options')
82
94
  .option('--base <branch>', 'Set default base branch')
83
95
  .option('--mode <mode>', 'Set default mode (fast/smart/full)')
84
96
  .option('--depth <number>', 'Set default smart-mode depth (1-10)')
97
+ .addOption(new Option('--jest <value>', 'Set default extra Jest CLI flag, e.g. --maxWorkers=2 (repeatable or comma-separated)').argParser(collectJest))
98
+ .option('--filter <regex>', 'Set default spec filter regex matched against the final selected spec files')
85
99
  .action((opts) => {
86
100
  let config = readConfig();
87
101
 
@@ -89,7 +103,7 @@ program
89
103
 
90
104
  if (opts.base) {
91
105
  verifyBaseBranchExists(opts.base);
92
-
106
+
93
107
  config.base = opts.base;
94
108
  updated = true;
95
109
  console.log(`Default base branch set to: ${opts.base}`);
@@ -116,6 +130,18 @@ program
116
130
  updated = true;
117
131
  console.log(`Default smart-mode depth set to: ${config.depth}`);
118
132
  }
133
+
134
+ if (configCommand.getOptionValueSource('filter') === 'cli') {
135
+ config.filter = opts.filter;
136
+ updated = true;
137
+ console.log(`Default spec filter set to: ${opts.filter}`);
138
+ }
139
+
140
+ if (configCommand.getOptionValueSource('jest') === 'cli') {
141
+ config.jest = opts.jest;
142
+ updated = true;
143
+ console.log(`Default Jest flags set to: ${opts.jest.join(' ')}`);
144
+ }
119
145
  if (updated) {
120
146
  writeConfig(config);
121
147
  } else {
@@ -133,7 +159,8 @@ program.action((opts) => {
133
159
 
134
160
  const modeFromCli = program.getOptionValueSource('mode') === 'cli';
135
161
  const depthFromCli = program.getOptionValueSource('depth') === 'cli';
136
-
162
+ const jestFromCli = program.getOptionValueSource('jest') === 'cli';
163
+
137
164
  // Use config base if not provided in CLI
138
165
  if (!options.base && config.base) {
139
166
  options.base = config.base;
@@ -145,6 +172,14 @@ program.action((opts) => {
145
172
  options.mode = config.mode;
146
173
  }
147
174
 
175
+ if (!jestFromCli && config.jest !== undefined && config.jest !== null) {
176
+ options.jest = config.jest;
177
+ }
178
+
179
+ if (!options.filter && config.filter) {
180
+ options.filter = config.filter;
181
+ }
182
+
148
183
  options.mode = String(options.mode || 'smart').toLowerCase();
149
184
  if (!['fast', 'smart', 'full'].includes(options.mode)) {
150
185
  console.error(`Invalid mode: ${options.mode}. Expected one of: fast, smart, full.`);
@@ -24,14 +24,21 @@ const modeField = z.string().optional().describe(
24
24
  const depthField = z.union([z.number(), z.string()]).optional().describe(
25
25
  'Smart-mode reverse-import depth, an integer from 1 to 10. 1 = tests that import the file. 2 (default) = also one intermediate module.'
26
26
  );
27
+ const jestArgsField = z.union([z.array(z.string()), z.string()]).optional().describe(
28
+ 'Extra Jest CLI flags to pass through, e.g. ["--maxWorkers=4","--silent"] or "--maxWorkers=4,--silent". Appended to the tool\'s own Jest arguments.'
29
+ );
30
+ const filterField = z.string().optional().describe(
31
+ 'Regular expression matched against the final list of selected spec files; only matching test paths run. Example: "src/__tests__/login". Reads "filter" from .mo3ta-coverage.json when not passed explicitly.'
32
+ );
27
33
  const useConfigField = z.boolean().optional().describe(
28
- 'Read base, mode, and depth defaults from .mo3ta-coverage.json in the repo. Default true. Explicit arguments override the file. Set false to ignore a broken config.'
34
+ 'Read base, mode, depth, jest, and filter defaults from .mo3ta-coverage.json in the repo. Default true. Explicit arguments override the file. Set false to ignore a broken config.'
29
35
  );
30
36
 
31
37
  const INSTRUCTIONS = [
32
38
  'mo3ta-coverage checks coverage of lines changed versus a base ref.',
33
39
  'Use list_changed_files to see changed JS/TS files, map_related_tests to see which tests would run, and check_changed_line_coverage to get the uncovered changed lines to write tests for.',
34
40
  'check_changed_line_coverage runs the repo\'s local Jest and writes coverage/ in that repo. Pass runTests: false to read an existing lcov file instead.',
41
+ 'Pass a filter (a regex) to map_related_tests or check_changed_line_coverage to narrow the final list of selected spec files to the matching paths. The result includes allTestsToRun (before the filter) and testsToRun (after) so you can validate the match.',
35
42
  'A result with ok: false and uncovered lines is a coverage gap, not a crashed tool. Operational problems (not a git repo, bad base ref, Jest missing) come back as tool errors with a code and a hint.'
36
43
  ].join(' ');
37
44
 
@@ -103,7 +110,7 @@ export function createServer({ version = '0.0.0' } = {}) {
103
110
  'map_related_tests',
104
111
  {
105
112
  title: 'Map related tests',
106
- description: 'Map changed source files to the test files fast, smart, or full mode would run. smart (default) uses filenames plus a depth-limited reverse-import walk. full cannot list Jest\'s expanded set until tests actually run. Does not run Jest or read coverage.',
113
+ description: 'Map changed source files to the test files fast, smart, or full mode would run. smart (default) uses filenames plus a depth-limited reverse-import walk. full cannot list Jest\'s expanded set until tests actually run. Pass filter (a regex) to narrow the selected spec files to matching paths. Does not run Jest or read coverage.',
107
114
  annotations: {
108
115
  readOnlyHint: true,
109
116
  destructiveHint: false,
@@ -117,6 +124,7 @@ export function createServer({ version = '0.0.0' } = {}) {
117
124
  filesFrom: filesFromField,
118
125
  mode: modeField,
119
126
  depth: depthField,
127
+ filter: filterField,
120
128
  useConfig: useConfigField
121
129
  }
122
130
  },
@@ -159,6 +167,8 @@ export function createServer({ version = '0.0.0' } = {}) {
159
167
  ciReport: z.string().optional().describe(
160
168
  'Also write the CLI markdown table to this path (relative to root). Omitted by default so the tool does not create a report file.'
161
169
  ),
170
+ jest: jestArgsField,
171
+ filter: filterField,
162
172
  useConfig: useConfigField
163
173
  }
164
174
  },
@@ -117,6 +117,34 @@ test('list and map tools return changed files and their tests', async () => {
117
117
  }
118
118
  });
119
119
 
120
+ test('map_related_tests narrows the selected specs with a filter regex', async () => {
121
+ const root = initFixture();
122
+ fs.writeFileSync(path.join(root, 'src', 'other.test.js'), [
123
+ "const { add } = require('./math');",
124
+ "test('other', () => {",
125
+ ' expect(add(1, 1)).toBe(2);',
126
+ '});',
127
+ ''
128
+ ].join('\n'));
129
+ git(root, 'git add src/other.test.js && git commit -q -m other');
130
+ const session = await connect();
131
+ try {
132
+ const mapped = await session.client.callTool({
133
+ name: 'map_related_tests',
134
+ arguments: { root, base: 'main', mode: 'fast', filter: 'math', useConfig: false }
135
+ });
136
+ const data = dataOf(mapped);
137
+ assert.equal(mapped.isError, false);
138
+ assert.equal(data.filter, 'math');
139
+ assert.deepEqual(data.testsToRun, ['src/math.test.js']);
140
+ assert.ok(data.allTestsToRun.includes('src/other.test.js'));
141
+ assert.match(data.summary, /Filter \/math\/ kept 1 of 2/);
142
+ } finally {
143
+ await session.close();
144
+ fs.rmSync(root, { recursive: true, force: true });
145
+ }
146
+ });
147
+
120
148
  test('turns a missing repo and a bad base ref into tool errors', async () => {
121
149
  const session = await connect();
122
150
  const missing = fs.mkdtempSync(path.join(os.tmpdir(), 'mo3ta-mcp-missing-'));
@@ -169,11 +197,13 @@ test('check_changed_line_coverage runs Jest and returns the uncovered line', asy
169
197
  mode: 'fast',
170
198
  limit: 100,
171
199
  useConfig: false,
172
- timeoutMs: 120000
200
+ timeoutMs: 120000,
201
+ jest: ['--silent']
173
202
  }
174
203
  });
175
204
  const data = dataOf(result);
176
205
  assert.equal(result.isError, false);
206
+ assert.deepEqual(data.jestArgs, ['--silent']);
177
207
  assert.equal(data.testsFailed, false);
178
208
  assert.equal(data.jest.ran, true);
179
209
  assert.equal(data.coveragePassed, false);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "mo3ta-coverage",
3
- "version": "1.3.0",
3
+ "version": "1.3.3",
4
4
  "description": "Run tests and report uncovered changed lines in a PR",
5
5
  "homepage": "https://mo3ta.top/mo3ta-coverage/",
6
6
  "main": "index.js",
package/src/api.js CHANGED
@@ -10,6 +10,8 @@ import {
10
10
  getExplicitFiles,
11
11
  listChangedSourceFiles,
12
12
  loadCoverageIndex,
13
+ parseJestArgs,
14
+ parseFilter,
13
15
  resolveJestBin,
14
16
  resolveTestPlan,
15
17
  summarizeChangedLineResults,
@@ -99,7 +101,7 @@ function readProjectConfig(root, useConfig) {
99
101
  throw new Mo3taError(
100
102
  `Could not parse ${configPath}: ${error.message}`,
101
103
  'INVALID_CONFIG',
102
- 'Fix .mo3ta-coverage.json or call the tool with useConfig: false. The file only supplies base, mode, and depth.'
104
+ 'Fix .mo3ta-coverage.json or call the tool with useConfig: false. The file only supplies base, mode, depth, jest, and filter.'
103
105
  );
104
106
  }
105
107
 
@@ -115,7 +117,9 @@ function readProjectConfig(root, useConfig) {
115
117
  config: {
116
118
  base: parsed.base,
117
119
  mode: parsed.mode,
118
- depth: parsed.depth
120
+ depth: parsed.depth,
121
+ jest: parsed.jest,
122
+ filter: parsed.filter
119
123
  },
120
124
  configPath,
121
125
  found: true,
@@ -230,6 +234,24 @@ function openRepo(options = {}) {
230
234
  ? String(options.base)
231
235
  : config.base || DEFAULT_BASE;
232
236
 
237
+ const rawFilter = options.filter !== undefined && options.filter !== null && options.filter !== ''
238
+ ? options.filter
239
+ : (config.filter || null);
240
+ // Validate up front so a bad regex never reaches resolveTestPlan.
241
+ let filter = null;
242
+ try {
243
+ filter = parseFilter(rawFilter);
244
+ } catch (error) {
245
+ if (error.code === 'INVALID_FILTER') {
246
+ throw new Mo3taError(
247
+ error.message,
248
+ 'INVALID_FILTER',
249
+ 'filter is a JavaScript regular expression matched against the repo-relative spec file paths, e.g. "src/__tests__/login".'
250
+ );
251
+ }
252
+ throw error;
253
+ }
254
+
233
255
  assertGitRepo(root);
234
256
  assertBase(base, root);
235
257
 
@@ -242,6 +264,10 @@ function openRepo(options = {}) {
242
264
  lcov: options.lcov ? String(options.lcov) : DEFAULT_LCOV,
243
265
  runTests: options.runTests !== false && options.runTests !== 'false',
244
266
  showCovered: options.showCovered === true || options.showCovered === 'true',
267
+ jestArgs: parseJestArgs(
268
+ options.jest !== undefined && options.jest !== null ? options.jest : config.jest
269
+ ),
270
+ filter,
245
271
  timeoutMs,
246
272
  ciReport: options.ciReport ? String(options.ciReport) : null,
247
273
  configFound: found,
@@ -323,6 +349,8 @@ function settingsView(ctx) {
323
349
  depth: ctx.depth,
324
350
  limit: ctx.limit,
325
351
  lcov: ctx.lcov,
352
+ jestArgs: ctx.jestArgs,
353
+ filter: ctx.filter ? String(ctx.filter) : null,
326
354
  configFound: ctx.configFound,
327
355
  configUsed: ctx.configUsed
328
356
  };
@@ -417,11 +445,14 @@ function summarizePlan(result) {
417
445
  const header = result.delegatedToJest
418
446
  ? `full mode passes ${result.jestTargets.length} changed file(s) to jest --findRelatedTests. Without running Jest, only ${result.testsToRun.length} changed test file(s) are known.`
419
447
  : `${result.testsToRun.length} test file(s) selected in ${result.mode} mode${result.mode === 'smart' ? ` (depth ${result.depth})` : ''}.`;
448
+ const filterLine = result.filter
449
+ ? `Filter /${result.filter}/ kept ${result.testsToRun.length} of ${result.allTestsToRun.length} candidate test file(s).`
450
+ : null;
420
451
  const mappingLines = result.mappings.slice(0, 30).map(mapping => {
421
452
  if (mapping.tests.length === 0) return `- ${mapping.source} → no test file (${mapping.matchType})`;
422
453
  return `- ${mapping.source} → ${mapping.tests.join(', ')} (${mapping.matchType})`;
423
454
  });
424
- return [header, result.warning, ...mappingLines].filter(Boolean).join('\n');
455
+ return [header, filterLine, result.warning, ...mappingLines].filter(Boolean).join('\n');
425
456
  }
426
457
 
427
458
  function summarizeCheck(result) {
@@ -489,6 +520,8 @@ function presentPlan(ctx, selected, plan) {
489
520
  matchType: mapping.matchType,
490
521
  tests: mapping.tests
491
522
  })),
523
+ filter: plan.filter,
524
+ allTestsToRun: plan.allTestsToRun,
492
525
  testsToRun: plan.testsToRun,
493
526
  jestTargets: plan.jestTargets,
494
527
  warning
@@ -526,10 +559,35 @@ export function listChangedFiles(options = {}) {
526
559
  export function mapRelatedTests(options = {}) {
527
560
  const ctx = openRepo(options);
528
561
  const selected = selectInputFiles(ctx, options);
529
- const plan = resolveTestPlan(selected.files, ctx.mode, ctx.depth ?? 2, ctx.root);
562
+ const plan = resolveTestPlan(selected.files, ctx.mode, ctx.depth ?? 2, ctx.root, ctx.jestArgs, ctx.filter);
530
563
  return presentPlan(ctx, selected, plan);
531
564
  }
532
565
 
566
+ /**
567
+ * Builds the argument array for a captured (non-interactive) Jest run.
568
+ * Always disables watch mode. Adds `--runInBand` unless the caller already
569
+ * chose a worker strategy, because Jest rejects `--runInBand` together with
570
+ * `--maxWorkers` ("only one is allowed").
571
+ * @param {string[]} [jestArgs]
572
+ * @returns {string[]}
573
+ */
574
+ export function buildCapturedJestArgs(jestArgs = []) {
575
+ const callerSetsWorkers = jestArgs.some(arg =>
576
+ arg === '--runInBand' ||
577
+ arg === '-i' ||
578
+ arg === '--maxWorkers' ||
579
+ arg === '-w' ||
580
+ arg.startsWith('--maxWorkers=') ||
581
+ arg.startsWith('-w=')
582
+ );
583
+
584
+ return [
585
+ ...jestArgs,
586
+ '--watchAll=false',
587
+ ...(callerSetsWorkers ? [] : ['--runInBand'])
588
+ ];
589
+ }
590
+
533
591
  function runJestCaptured(ctx, jestArgs) {
534
592
  const jestBin = resolveJestBin(ctx.root);
535
593
  if (!fs.existsSync(jestBin)) {
@@ -541,9 +599,9 @@ function runJestCaptured(ctx, jestArgs) {
541
599
  }
542
600
 
543
601
  // --watchAll=false keeps a non-interactive server from sitting in watch mode.
544
- // --runInBand keeps Jest in one process so a timeout can actually stop it.
545
- // Neither flag changes which tests or lines the CLI's own arguments select.
546
- const args = [...jestArgs, '--watchAll=false', '--runInBand'];
602
+ // --runInBand keeps Jest in one process so a timeout can actually stop it,
603
+ // but it is dropped when the caller picked a worker strategy (they conflict).
604
+ const args = buildCapturedJestArgs(jestArgs);
547
605
  try {
548
606
  const stdout = execFileSync(process.execPath, [jestBin, ...args], {
549
607
  cwd: ctx.root,
@@ -639,7 +697,7 @@ export function checkChangedLineCoverage(options = {}) {
639
697
  return result;
640
698
  }
641
699
 
642
- const plan = resolveTestPlan(selected.files, ctx.mode, ctx.depth ?? 2, ctx.root);
700
+ const plan = resolveTestPlan(selected.files, ctx.mode, ctx.depth ?? 2, ctx.root, ctx.jestArgs, ctx.filter);
643
701
  const nothingToRun = plan.delegatedToJest
644
702
  ? plan.jestTargets.length === 0
645
703
  : plan.testsToRun.length === 0;
@@ -658,10 +716,12 @@ export function checkChangedLineCoverage(options = {}) {
658
716
  cliWouldExit: 0,
659
717
  warnings: [
660
718
  ...warnings,
661
- 'No test files were selected, so Jest did not run. The CLI exits 0 in this case and never measures coverage. Add a test that imports the changed file.'
719
+ 'No test files were selected, so Jest did not run. The CLI exits 0 in this case and never measures coverage. Add a test that imports the changed file.' +
720
+ (plan.filter ? ` All candidate test files were dropped by the filter /${plan.filter}/.` : '')
662
721
  ],
663
722
  mappings: plan.mappings,
664
723
  testsToRun: plan.testsToRun,
724
+ allTestsToRun: plan.allTestsToRun,
665
725
  files: filesWithoutCoverageRun(ctx, plan, budget),
666
726
  totals: { changed: 0, covered: 0, uncovered: 0, coverage: null },
667
727
  jest: { ran: false, testsFailed: false, outputTail: '', outputTruncated: false }
@@ -725,12 +785,14 @@ export function checkChangedLineCoverage(options = {}) {
725
785
  cliWouldExit,
726
786
  warnings,
727
787
  ciReport: ctx.ciReport ? path.resolve(ctx.root, ctx.ciReport) : null,
788
+ filter: plan.filter,
728
789
  mappings: plan.mappings.map(mapping => ({
729
790
  source: mapping.source,
730
791
  matchType: mapping.matchType,
731
792
  tests: mapping.tests
732
793
  })),
733
794
  testsToRun: plan.testsToRun,
795
+ allTestsToRun: plan.allTestsToRun,
734
796
  files,
735
797
  totals: {
736
798
  changed: totals.totalChanged,