mo3ta-coverage 1.2.1 → 1.3.0

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/src/api.js ADDED
@@ -0,0 +1,745 @@
1
+ import { execFileSync } from 'child_process';
2
+ import fs from 'fs';
3
+ import path from 'path';
4
+ import { checkBaseRef, checkGitRepository } from './gitUtils.js';
5
+ import { clearScanCaches, separateSourceAndTestFiles } from './fileUtils.js';
6
+ import {
7
+ analyzeChangedFile,
8
+ buildMarkdownCoverageReport,
9
+ getChangedLines,
10
+ getExplicitFiles,
11
+ listChangedSourceFiles,
12
+ loadCoverageIndex,
13
+ resolveJestBin,
14
+ resolveTestPlan,
15
+ summarizeChangedLineResults,
16
+ writeMarkdownReport
17
+ } from './cli.js';
18
+
19
+ const DEFAULT_BASE = 'origin/main';
20
+ const DEFAULT_LIMIT = 80;
21
+ const DEFAULT_LCOV = 'coverage/lcov.info';
22
+ const DEFAULT_TIMEOUT_MS = 300000;
23
+ const MAX_TIMEOUT_MS = 30 * 60 * 1000;
24
+ const JEST_MAX_BUFFER = 20 * 1024 * 1024;
25
+ const OUTPUT_TAIL_CHARS = 8000;
26
+ const MAX_LINES_RETURNED = 100;
27
+ const MAX_SNIPPETS_PER_FILE = 20;
28
+ const MAX_SNIPPETS_TOTAL = 60;
29
+ const MAX_SNIPPET_CHARS = 180;
30
+ const CONFIG_NAME = '.mo3ta-coverage.json';
31
+
32
+ /**
33
+ * Failure the CLI would print and exit on. `code` is stable for agents.
34
+ */
35
+ export class Mo3taError extends Error {
36
+ constructor(message, code, hint, extra = {}) {
37
+ super(message);
38
+ this.name = 'Mo3taError';
39
+ this.code = code;
40
+ this.hint = hint || null;
41
+ if (extra.jest) this.jest = extra.jest;
42
+ }
43
+ }
44
+
45
+ /**
46
+ * Repo the tool should inspect. An explicit `root` wins, then Claude Code's
47
+ * project directory, then the server process cwd.
48
+ * @param {string} [root]
49
+ * @returns {string}
50
+ */
51
+ export function resolveRepoRoot(root) {
52
+ if (root !== undefined && root !== null && String(root).trim() !== '') {
53
+ return path.resolve(String(root));
54
+ }
55
+ const claudeRoot = process.env.CLAUDE_PROJECT_DIR;
56
+ if (claudeRoot && String(claudeRoot).trim() !== '') {
57
+ return path.resolve(String(claudeRoot));
58
+ }
59
+ return process.cwd();
60
+ }
61
+
62
+ function stripAnsi(text) {
63
+ return String(text || '').replace(/\u001b\[[0-9;]*m/g, '');
64
+ }
65
+
66
+ function round2(value) {
67
+ if (value === null || value === undefined || Number.isNaN(value)) return null;
68
+ return Math.round(value * 100) / 100;
69
+ }
70
+
71
+ function capList(values, max = MAX_LINES_RETURNED) {
72
+ return values.slice(0, max);
73
+ }
74
+
75
+ function clipOutput(text) {
76
+ const clean = stripAnsi(text).trim();
77
+ if (clean.length <= OUTPUT_TAIL_CHARS) {
78
+ return { outputTail: clean, outputTruncated: false };
79
+ }
80
+ return {
81
+ outputTail: clean.slice(-OUTPUT_TAIL_CHARS),
82
+ outputTruncated: true
83
+ };
84
+ }
85
+
86
+ function readProjectConfig(root, useConfig) {
87
+ const configPath = path.resolve(root, CONFIG_NAME);
88
+ if (useConfig === false) {
89
+ return { config: {}, configPath, found: false, used: false };
90
+ }
91
+ if (!fs.existsSync(configPath)) {
92
+ return { config: {}, configPath, found: false, used: true };
93
+ }
94
+
95
+ let parsed;
96
+ try {
97
+ parsed = JSON.parse(fs.readFileSync(configPath, 'utf8'));
98
+ } catch (error) {
99
+ throw new Mo3taError(
100
+ `Could not parse ${configPath}: ${error.message}`,
101
+ 'INVALID_CONFIG',
102
+ 'Fix .mo3ta-coverage.json or call the tool with useConfig: false. The file only supplies base, mode, and depth.'
103
+ );
104
+ }
105
+
106
+ if (parsed === null || typeof parsed !== 'object' || Array.isArray(parsed)) {
107
+ throw new Mo3taError(
108
+ `Could not parse ${configPath}: expected a JSON object.`,
109
+ 'INVALID_CONFIG',
110
+ 'Fix .mo3ta-coverage.json or call the tool with useConfig: false.'
111
+ );
112
+ }
113
+
114
+ return {
115
+ config: {
116
+ base: parsed.base,
117
+ mode: parsed.mode,
118
+ depth: parsed.depth
119
+ },
120
+ configPath,
121
+ found: true,
122
+ used: true
123
+ };
124
+ }
125
+
126
+ function parseMode(explicit, configMode) {
127
+ const raw = explicit !== undefined && explicit !== null && explicit !== ''
128
+ ? explicit
129
+ : configMode || 'smart';
130
+ const mode = String(raw).toLowerCase();
131
+ if (!['fast', 'smart', 'full'].includes(mode)) {
132
+ throw new Mo3taError(
133
+ `Invalid mode: ${raw}. Expected one of: fast, smart, full.`,
134
+ 'INVALID_MODE',
135
+ 'fast maps by filename and a direct import scan. smart adds a depth-limited reverse-import walk. full passes changed files to jest --findRelatedTests.'
136
+ );
137
+ }
138
+ return mode;
139
+ }
140
+
141
+ function parseDepth(explicit, configDepth, mode) {
142
+ if (mode !== 'smart') return null;
143
+ const raw = explicit !== undefined && explicit !== null && explicit !== ''
144
+ ? explicit
145
+ : configDepth !== undefined ? configDepth : 2;
146
+ const depth = Number.parseInt(raw, 10);
147
+ if (!Number.isInteger(depth) || depth < 1 || depth > 10) {
148
+ throw new Mo3taError(
149
+ `Invalid depth: ${raw}. Expected an integer between 1 and 10.`,
150
+ 'INVALID_DEPTH',
151
+ 'Depth 1 keeps tests that import the changed file. Depth 2 also walks one intermediate module, such as a barrel index.js.'
152
+ );
153
+ }
154
+ return depth;
155
+ }
156
+
157
+ function parseLimit(value) {
158
+ if (value === undefined || value === null || value === '') return DEFAULT_LIMIT;
159
+ const limit = typeof value === 'number' ? value : Number.parseFloat(value);
160
+ if (!Number.isFinite(limit) || limit < 0 || limit > 100) {
161
+ throw new Mo3taError(
162
+ `Invalid limit: ${value}. Expected a number from 0 to 100.`,
163
+ 'INVALID_LIMIT',
164
+ 'The limit is the minimum percent of changed, coverable lines that must be covered.'
165
+ );
166
+ }
167
+ return limit;
168
+ }
169
+
170
+ function parseTimeout(value) {
171
+ if (value === undefined || value === null || value === '') return DEFAULT_TIMEOUT_MS;
172
+ const timeout = typeof value === 'number' ? value : Number.parseInt(value, 10);
173
+ if (!Number.isInteger(timeout) || timeout < 1000 || timeout > MAX_TIMEOUT_MS) {
174
+ throw new Mo3taError(
175
+ `Invalid timeoutMs: ${value}. Expected an integer from 1000 to ${MAX_TIMEOUT_MS}.`,
176
+ 'INVALID_TIMEOUT',
177
+ 'Jest is killed when this elapses. Narrow the run with mode "fast" or an explicit files list before raising it.'
178
+ );
179
+ }
180
+ return timeout;
181
+ }
182
+
183
+ function assertDirectory(root) {
184
+ if (!fs.existsSync(root) || !fs.statSync(root).isDirectory()) {
185
+ throw new Mo3taError(
186
+ `Repository path does not exist or is not a directory: ${root}`,
187
+ 'REPO_NOT_FOUND',
188
+ 'Pass root as the git checkout to inspect. When root is omitted, the server uses CLAUDE_PROJECT_DIR if set, otherwise its own cwd.'
189
+ );
190
+ }
191
+ }
192
+
193
+ function assertGitRepo(root) {
194
+ const git = checkGitRepository(root);
195
+ if (!git.ok) {
196
+ throw new Mo3taError(
197
+ `${root} is not a git repository.`,
198
+ 'NOT_A_GIT_REPO',
199
+ 'mo3ta-coverage compares files with git. Pass root as a local checkout (the folder that contains .git).'
200
+ );
201
+ }
202
+ }
203
+
204
+ function assertBase(base, root) {
205
+ const result = checkBaseRef(base, root);
206
+ if (!result.ok) {
207
+ throw new Mo3taError(
208
+ `Base ref "${base}" does not exist in ${root}.`,
209
+ 'INVALID_BASE_REF',
210
+ 'Fetch the ref (git fetch) or pass a local branch, tag, or commit. origin/main is the default and is missing until that remote ref exists locally.'
211
+ );
212
+ }
213
+ }
214
+
215
+ /**
216
+ * Shared option resolution for every tool. Clears scan caches so a long-running
217
+ * server sees edits made since the previous call.
218
+ */
219
+ function openRepo(options = {}) {
220
+ clearScanCaches();
221
+ const root = resolveRepoRoot(options.root);
222
+ assertDirectory(root);
223
+
224
+ const { config, configPath, found, used } = readProjectConfig(root, options.useConfig);
225
+ const mode = parseMode(options.mode, config.mode);
226
+ const depth = parseDepth(options.depth, config.depth, mode);
227
+ const limit = parseLimit(options.limit);
228
+ const timeoutMs = parseTimeout(options.timeoutMs);
229
+ const base = options.base !== undefined && options.base !== null && options.base !== ''
230
+ ? String(options.base)
231
+ : config.base || DEFAULT_BASE;
232
+
233
+ assertGitRepo(root);
234
+ assertBase(base, root);
235
+
236
+ return {
237
+ root,
238
+ base,
239
+ mode,
240
+ depth,
241
+ limit,
242
+ lcov: options.lcov ? String(options.lcov) : DEFAULT_LCOV,
243
+ runTests: options.runTests !== false && options.runTests !== 'false',
244
+ showCovered: options.showCovered === true || options.showCovered === 'true',
245
+ timeoutMs,
246
+ ciReport: options.ciReport ? String(options.ciReport) : null,
247
+ configFound: found,
248
+ configUsed: used,
249
+ configPath
250
+ };
251
+ }
252
+
253
+ function explicitListRequested(options) {
254
+ const filesGiven = options.files !== undefined && options.files !== null && options.files !== false && options.files !== '';
255
+ return filesGiven || Boolean(options.filesFrom);
256
+ }
257
+
258
+ function selectInputFiles(ctx, options) {
259
+ let explicit = [];
260
+ try {
261
+ explicit = getExplicitFiles({
262
+ files: options.files,
263
+ filesFrom: options.filesFrom
264
+ }, ctx.root);
265
+ } catch (error) {
266
+ if (error.code === 'ENOENT') {
267
+ throw new Mo3taError(
268
+ `Could not read the file list at ${options.filesFrom}.`,
269
+ 'FILE_LIST_NOT_FOUND',
270
+ 'Pass filesFrom as a path relative to the repo root, or pass files instead.'
271
+ );
272
+ }
273
+ throw new Mo3taError(
274
+ error.message || 'Could not read the explicit file list.',
275
+ 'FILE_LIST_INVALID',
276
+ 'files accepts a string array or a comma-separated string of repo-relative paths.'
277
+ );
278
+ }
279
+
280
+ if (explicitListRequested(options)) {
281
+ // Unlike the CLI, an explicit list that normalizes to nothing does not
282
+ // silently fall back to git detection. An agent that passed the wrong
283
+ // paths should see that, not a scan of the whole branch.
284
+ return {
285
+ files: explicit,
286
+ detection: 'explicit',
287
+ warning: explicit.length === 0
288
+ ? 'The explicit file list was empty after normalization (missing paths, or only node_modules/coverage/dist/build entries). Git changed-file detection was not used.'
289
+ : null
290
+ };
291
+ }
292
+
293
+ try {
294
+ return {
295
+ files: listChangedSourceFiles(ctx.base, ctx.root),
296
+ detection: 'git',
297
+ warning: null
298
+ };
299
+ } catch (error) {
300
+ throw new Mo3taError(
301
+ `Git could not list files changed against ${ctx.base}. ${error.message || ''}`.trim(),
302
+ 'GIT_ERROR',
303
+ 'Fetch the base ref and make sure HEAD exists. Changed files are the merge-base..HEAD diff plus staged and unstaged edits.'
304
+ );
305
+ }
306
+ }
307
+
308
+ function classifySelected(files) {
309
+ const { sourceFiles, testFiles } = separateSourceAndTestFiles(files);
310
+ const known = new Set([...sourceFiles, ...testFiles]);
311
+ return files.map(filePath => ({
312
+ path: filePath,
313
+ kind: sourceFiles.includes(filePath) ? 'source' : testFiles.includes(filePath) ? 'test' : 'skipped',
314
+ reason: known.has(filePath) ? null : 'Config and JSON files are ignored by test selection and by the coverage check.'
315
+ }));
316
+ }
317
+
318
+ function settingsView(ctx) {
319
+ return {
320
+ root: ctx.root,
321
+ base: ctx.base,
322
+ mode: ctx.mode,
323
+ depth: ctx.depth,
324
+ limit: ctx.limit,
325
+ lcov: ctx.lcov,
326
+ configFound: ctx.configFound,
327
+ configUsed: ctx.configUsed
328
+ };
329
+ }
330
+
331
+ function takeSnippets(root, relPath, lines, budget) {
332
+ let rows = null;
333
+ try {
334
+ rows = fs.readFileSync(path.resolve(root, relPath), 'utf8').split(/\r?\n/);
335
+ } catch {
336
+ rows = null;
337
+ }
338
+
339
+ const snippets = [];
340
+ let truncated = false;
341
+ for (const line of lines) {
342
+ if (snippets.length >= MAX_SNIPPETS_PER_FILE || budget.remaining <= 0) {
343
+ truncated = true;
344
+ break;
345
+ }
346
+ const raw = rows ? (rows[line - 1] ?? '') : '';
347
+ snippets.push({
348
+ line,
349
+ text: raw.length > MAX_SNIPPET_CHARS ? `${raw.slice(0, MAX_SNIPPET_CHARS)}…` : raw
350
+ });
351
+ budget.remaining -= 1;
352
+ }
353
+ if (lines.length > snippets.length) truncated = true;
354
+ return { snippets, truncated };
355
+ }
356
+
357
+ function diffLines(relPath, base, root) {
358
+ try {
359
+ return getChangedLines(relPath, base, root);
360
+ } catch (error) {
361
+ throw new Mo3taError(
362
+ `Git could not diff ${relPath} against ${base}. ${error.message || ''}`.trim(),
363
+ 'GIT_ERROR',
364
+ 'The path should be relative to the repo root, and the base ref must resolve to a commit.'
365
+ );
366
+ }
367
+ }
368
+
369
+ function presentAnalyzedFile(result, ctx, budget) {
370
+ const uncovered = takeSnippets(ctx.root, result.filePath, result.uncoveredLines, budget);
371
+ const presented = {
372
+ file: result.filePath,
373
+ absolutePath: result.absolutePath,
374
+ changedLines: capList(result.changedLines),
375
+ changedLinesTruncated: result.changedLines.length > MAX_LINES_RETURNED,
376
+ hasCoverageInfo: result.hasCoverageInfo,
377
+ changedCoverableLines: result.trackedChangedLines,
378
+ coveredCount: result.coveredLines.length,
379
+ uncoveredCount: result.uncoveredLines.length,
380
+ coverage: result.trackedChangedLines > 0
381
+ ? round2((result.coveredLines.length / result.trackedChangedLines) * 100)
382
+ : null,
383
+ uncoveredLines: capList(result.uncoveredLines),
384
+ uncoveredLinesTruncated: result.uncoveredLines.length > MAX_LINES_RETURNED,
385
+ uncovered: uncovered.snippets,
386
+ uncoveredTruncated: uncovered.truncated
387
+ };
388
+
389
+ if (!result.hasCoverageInfo) {
390
+ presented.note = 'No lcov record for this file. changedLines come from the git diff and were not counted toward the threshold (same as the CLI).';
391
+ } else if (result.trackedChangedLines === 0 && result.changedLines.length > 0) {
392
+ presented.note = 'The git diff has no coverable lines (for example imports or comments), so this file does not affect the threshold.';
393
+ }
394
+
395
+ if (ctx.showCovered) {
396
+ presented.coveredLines = capList(result.coveredLines);
397
+ presented.coveredLinesTruncated = result.coveredLines.length > MAX_LINES_RETURNED;
398
+ }
399
+
400
+ return presented;
401
+ }
402
+
403
+ function summarizeList(result) {
404
+ if (result.files.length === 0) {
405
+ return result.detection === 'explicit'
406
+ ? 'No scannable JS/TS files were left in the explicit list.'
407
+ : `No changed JS/TS files vs ${result.base}.`;
408
+ }
409
+ const lines = result.files.map(file => `- ${file.path} (${file.kind})`);
410
+ const head = result.detection === 'explicit'
411
+ ? `${result.files.length} explicit JS/TS file(s) in ${result.root}:`
412
+ : `${result.files.length} changed JS/TS file(s) vs ${result.base}:`;
413
+ return [head, ...lines].join('\n');
414
+ }
415
+
416
+ function summarizePlan(result) {
417
+ const header = result.delegatedToJest
418
+ ? `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
+ : `${result.testsToRun.length} test file(s) selected in ${result.mode} mode${result.mode === 'smart' ? ` (depth ${result.depth})` : ''}.`;
420
+ const mappingLines = result.mappings.slice(0, 30).map(mapping => {
421
+ if (mapping.tests.length === 0) return `- ${mapping.source} → no test file (${mapping.matchType})`;
422
+ return `- ${mapping.source} → ${mapping.tests.join(', ')} (${mapping.matchType})`;
423
+ });
424
+ return [header, result.warning, ...mappingLines].filter(Boolean).join('\n');
425
+ }
426
+
427
+ function summarizeCheck(result) {
428
+ if (result.noChangedFiles) {
429
+ if (result.warnings && result.warnings.length > 0) return result.warnings.join('\n');
430
+ return `No changed JS/TS files vs ${result.base}. Nothing to cover.`;
431
+ }
432
+ if (result.testsNotRunReason === 'no-tests') {
433
+ const lines = [
434
+ `No test files selected for mode ${result.mode}. Jest was not run, so changed-line coverage was not measured.`,
435
+ 'The CLI would exit 0 here. Write a test that imports the changed source, then run check_changed_line_coverage again.',
436
+ ...result.files.flatMap(file => [
437
+ `- ${file.file} changed lines: ${file.changedLines.slice(0, 15).join(', ') || '(none)'}`,
438
+ ...file.uncovered.slice(0, 6).map(snippet => ` ${file.file}:${snippet.line} ${snippet.text}`)
439
+ ])
440
+ ];
441
+ return lines.join('\n');
442
+ }
443
+
444
+ const coverage = result.totals.coverage;
445
+ const status = result.coveragePassed ? 'PASSED' : 'FAILED';
446
+ const percent = coverage === null ? 'n/a' : `${coverage.toFixed(2)}%`;
447
+ const lines = [
448
+ `Changed-line coverage ${status}: ${percent} (limit ${result.limit}%).`,
449
+ `${result.totals.covered} of ${result.totals.changed} coverable changed lines covered; ${result.totals.uncovered} uncovered.`
450
+ ];
451
+ if (result.testsFailed) {
452
+ lines.push('Jest reported failures. The line results below are from the lcov file it left behind.');
453
+ }
454
+ if (!result.runTests) {
455
+ lines.push('Jest was not run (runTests: false). Results come from the existing lcov file.');
456
+ }
457
+ result.files.filter(file => file.uncoveredLines.length > 0).forEach(file => {
458
+ lines.push(`${file.file} uncovered: ${file.uncoveredLines.slice(0, 20).join(', ')}`);
459
+ file.uncovered.slice(0, 8).forEach(snippet => {
460
+ lines.push(` ${file.file}:${snippet.line} ${snippet.text}`);
461
+ });
462
+ });
463
+ const missing = result.files.filter(file => file.hasCoverageInfo === false);
464
+ if (missing.length > 0) {
465
+ lines.push(`No lcov data for: ${missing.map(file => file.file).join(', ')}. Those diffs were not counted toward the threshold.`);
466
+ }
467
+ return lines.join('\n');
468
+ }
469
+
470
+ function presentPlan(ctx, selected, plan) {
471
+ const warning = [
472
+ selected.warning,
473
+ plan.delegatedToJest
474
+ ? 'full mode discovers related tests inside Jest --findRelatedTests. This list is only the changed test files, which is all --dryRun can know without running Jest.'
475
+ : null
476
+ ].filter(Boolean).join(' ') || null;
477
+ const result = {
478
+ ok: true,
479
+ root: ctx.root,
480
+ base: ctx.base,
481
+ mode: ctx.mode,
482
+ depth: ctx.depth,
483
+ detection: selected.detection,
484
+ delegatedToJest: plan.delegatedToJest,
485
+ sourceFiles: plan.sourceFiles,
486
+ changedTestFiles: plan.testFiles,
487
+ mappings: plan.mappings.map(mapping => ({
488
+ source: mapping.source,
489
+ matchType: mapping.matchType,
490
+ tests: mapping.tests
491
+ })),
492
+ testsToRun: plan.testsToRun,
493
+ jestTargets: plan.jestTargets,
494
+ warning
495
+ };
496
+ result.summary = summarizePlan(result);
497
+ return result;
498
+ }
499
+
500
+ /**
501
+ * JS/TS files changed vs a base ref, or an explicit list when `files` / `filesFrom` is set.
502
+ * Includes every author's commits since the merge base, plus staged and unstaged edits.
503
+ * @param {object} [options]
504
+ */
505
+ export function listChangedFiles(options = {}) {
506
+ const ctx = openRepo(options);
507
+ const selected = selectInputFiles(ctx, options);
508
+ const result = {
509
+ ok: true,
510
+ ...settingsView(ctx),
511
+ detection: selected.detection,
512
+ warning: selected.warning,
513
+ files: classifySelected(selected.files),
514
+ sourceFiles: separateSourceAndTestFiles(selected.files).sourceFiles,
515
+ testFiles: separateSourceAndTestFiles(selected.files).testFiles
516
+ };
517
+ result.summary = summarizeList(result);
518
+ return result;
519
+ }
520
+
521
+ /**
522
+ * Test files the selected mode would run for the changed (or explicit) sources.
523
+ * Does not run Jest and does not read lcov.
524
+ * @param {object} [options]
525
+ */
526
+ export function mapRelatedTests(options = {}) {
527
+ const ctx = openRepo(options);
528
+ const selected = selectInputFiles(ctx, options);
529
+ const plan = resolveTestPlan(selected.files, ctx.mode, ctx.depth ?? 2, ctx.root);
530
+ return presentPlan(ctx, selected, plan);
531
+ }
532
+
533
+ function runJestCaptured(ctx, jestArgs) {
534
+ const jestBin = resolveJestBin(ctx.root);
535
+ if (!fs.existsSync(jestBin)) {
536
+ throw new Mo3taError(
537
+ `Jest is not installed in ${ctx.root} (expected ${jestBin}).`,
538
+ 'JEST_NOT_FOUND',
539
+ 'Install dependencies in that repo so node_modules/jest/bin/jest.js exists. mo3ta-coverage runs the local Jest binary and does not download Jest.'
540
+ );
541
+ }
542
+
543
+ // --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'];
547
+ try {
548
+ const stdout = execFileSync(process.execPath, [jestBin, ...args], {
549
+ cwd: ctx.root,
550
+ timeout: ctx.timeoutMs,
551
+ killSignal: 'SIGKILL',
552
+ stdio: ['ignore', 'pipe', 'pipe'],
553
+ encoding: 'utf8',
554
+ maxBuffer: JEST_MAX_BUFFER,
555
+ env: { ...process.env, FORCE_COLOR: '0' }
556
+ });
557
+ return {
558
+ ran: true,
559
+ testsFailed: false,
560
+ timedOut: false,
561
+ ...clipOutput(stdout)
562
+ };
563
+ } catch (error) {
564
+ if (error.code === 'ETIMEDOUT') {
565
+ throw new Mo3taError(
566
+ `Jest exceeded ${ctx.timeoutMs}ms and was stopped.`,
567
+ 'JEST_TIMEOUT',
568
+ 'Raise timeoutMs (milliseconds, up to 30 minutes), use mode "fast", or pass files so fewer tests run.'
569
+ );
570
+ }
571
+ if (error.code === 'ERR_CHILD_PROCESS_STDIO_MAXBUFFER') {
572
+ throw new Mo3taError(
573
+ 'Jest produced more than 20MB of output, which is more than the MCP server keeps.',
574
+ 'JEST_OUTPUT_TOO_LARGE',
575
+ 'Re-run with a narrower files list or mode "fast". coverage/lcov.info may still have been written.'
576
+ );
577
+ }
578
+ const combined = `${error.stdout || ''}\n${error.stderr || ''}`;
579
+ return {
580
+ ran: true,
581
+ testsFailed: true,
582
+ timedOut: false,
583
+ exitCode: typeof error.status === 'number' ? error.status : 1,
584
+ ...clipOutput(combined)
585
+ };
586
+ }
587
+ }
588
+
589
+ function filesWithoutCoverageRun(ctx, plan, budget) {
590
+ return plan.sourceFiles.map(file => {
591
+ const changedLines = diffLines(file, ctx.base, ctx.root);
592
+ const snippets = takeSnippets(ctx.root, file, changedLines, budget);
593
+ return {
594
+ file,
595
+ absolutePath: path.resolve(ctx.root, file),
596
+ changedLines: capList(changedLines),
597
+ changedLinesTruncated: changedLines.length > MAX_LINES_RETURNED,
598
+ hasCoverageInfo: false,
599
+ changedCoverableLines: 0,
600
+ coveredCount: 0,
601
+ uncoveredCount: 0,
602
+ coverage: null,
603
+ uncoveredLines: [],
604
+ uncovered: snippets.snippets,
605
+ uncoveredTruncated: snippets.truncated,
606
+ note: 'No related test was run. These are changed lines from the git diff, not uncovered-line verdicts.'
607
+ };
608
+ });
609
+ }
610
+
611
+ /**
612
+ * Runs the changed-line coverage check and returns per-file uncovered lines.
613
+ * `runTests: false` only reads an existing lcov file. Jest writes `coverage/`
614
+ * inside the repo when tests run, same as the CLI.
615
+ * @param {object} [options]
616
+ */
617
+ export function checkChangedLineCoverage(options = {}) {
618
+ const ctx = openRepo(options);
619
+ const selected = selectInputFiles(ctx, options);
620
+ const warnings = selected.warning ? [selected.warning] : [];
621
+
622
+ if (selected.files.length === 0) {
623
+ const result = {
624
+ ok: true,
625
+ ...settingsView(ctx),
626
+ runTests: ctx.runTests,
627
+ detection: selected.detection,
628
+ noChangedFiles: true,
629
+ testsFailed: false,
630
+ testsNotRunReason: 'no-files',
631
+ coveragePassed: true,
632
+ cliWouldExit: 0,
633
+ warnings,
634
+ files: [],
635
+ totals: { changed: 0, covered: 0, uncovered: 0, coverage: null },
636
+ jest: { ran: false, testsFailed: false, outputTail: '', outputTruncated: false }
637
+ };
638
+ result.summary = summarizeCheck(result);
639
+ return result;
640
+ }
641
+
642
+ const plan = resolveTestPlan(selected.files, ctx.mode, ctx.depth ?? 2, ctx.root);
643
+ const nothingToRun = plan.delegatedToJest
644
+ ? plan.jestTargets.length === 0
645
+ : plan.testsToRun.length === 0;
646
+
647
+ if (ctx.runTests && nothingToRun) {
648
+ const budget = { remaining: MAX_SNIPPETS_TOTAL };
649
+ const result = {
650
+ ok: false,
651
+ ...settingsView(ctx),
652
+ runTests: true,
653
+ detection: selected.detection,
654
+ noChangedFiles: false,
655
+ testsFailed: false,
656
+ testsNotRunReason: 'no-tests',
657
+ coveragePassed: null,
658
+ cliWouldExit: 0,
659
+ warnings: [
660
+ ...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.'
662
+ ],
663
+ mappings: plan.mappings,
664
+ testsToRun: plan.testsToRun,
665
+ files: filesWithoutCoverageRun(ctx, plan, budget),
666
+ totals: { changed: 0, covered: 0, uncovered: 0, coverage: null },
667
+ jest: { ran: false, testsFailed: false, outputTail: '', outputTruncated: false }
668
+ };
669
+ result.summary = summarizeCheck(result);
670
+ return result;
671
+ }
672
+
673
+ let jest = { ran: false, testsFailed: false, outputTail: '', outputTruncated: false };
674
+ if (ctx.runTests) {
675
+ jest = runJestCaptured(ctx, plan.jestArgs);
676
+ }
677
+
678
+ let index;
679
+ try {
680
+ index = loadCoverageIndex(selected.files, ctx.lcov, ctx.root);
681
+ } catch (error) {
682
+ if (error.code === 'LCOV_NOT_FOUND') {
683
+ throw new Mo3taError(
684
+ `No lcov report at ${error.lcovPath}.`,
685
+ 'LCOV_NOT_FOUND',
686
+ jest.testsFailed
687
+ ? 'Jest failed before writing coverage. The tail of its output is in jest.outputTail. Fix the failure and run the check again.'
688
+ : 'Call the tool with runTests: true so Jest writes coverage/lcov.info, or pass lcov set to an existing report.',
689
+ { jest }
690
+ );
691
+ }
692
+ throw error;
693
+ }
694
+
695
+ const budget = { remaining: MAX_SNIPPETS_TOTAL };
696
+ const analyzed = [];
697
+ index.relevantFiles.forEach(relPath => {
698
+ analyzed.push(analyzeChangedFile(relPath, index.coverageByFile, ctx.base, ctx.root));
699
+ });
700
+ const totals = summarizeChangedLineResults(analyzed, ctx.limit);
701
+ const files = analyzed.map(result => presentAnalyzedFile(result, ctx, budget));
702
+
703
+ if (ctx.ciReport) {
704
+ const reportPath = path.resolve(ctx.root, ctx.ciReport);
705
+ const markdown = buildMarkdownCoverageReport(totals.rows, {
706
+ overallCoverage: totals.overallCoverage === null ? null : totals.overallCoverage.toFixed(2),
707
+ changedLinesLimit: ctx.limit,
708
+ totalChanged: totals.totalChanged,
709
+ totalNotCovered: totals.totalNotCovered
710
+ });
711
+ writeMarkdownReport(markdown, reportPath);
712
+ }
713
+
714
+ const coveragePassed = totals.passed;
715
+ const cliWouldExit = (jest.testsFailed || !coveragePassed) ? 1 : 0;
716
+ const result = {
717
+ ok: coveragePassed && !jest.testsFailed,
718
+ ...settingsView(ctx),
719
+ runTests: ctx.runTests,
720
+ detection: selected.detection,
721
+ noChangedFiles: false,
722
+ testsFailed: jest.testsFailed,
723
+ testsNotRunReason: ctx.runTests ? null : 'runTests-false',
724
+ coveragePassed,
725
+ cliWouldExit,
726
+ warnings,
727
+ ciReport: ctx.ciReport ? path.resolve(ctx.root, ctx.ciReport) : null,
728
+ mappings: plan.mappings.map(mapping => ({
729
+ source: mapping.source,
730
+ matchType: mapping.matchType,
731
+ tests: mapping.tests
732
+ })),
733
+ testsToRun: plan.testsToRun,
734
+ files,
735
+ totals: {
736
+ changed: totals.totalChanged,
737
+ covered: totals.totalChanged - totals.totalNotCovered,
738
+ uncovered: totals.totalNotCovered,
739
+ coverage: round2(totals.overallCoverage)
740
+ },
741
+ jest
742
+ };
743
+ result.summary = summarizeCheck(result);
744
+ return result;
745
+ }