pr-checkmate 3.3.0 → 4.0.1

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.
Files changed (127) hide show
  1. package/LICENSE +8 -3
  2. package/README.md +59 -4
  3. package/cspell.json +1 -0
  4. package/dist/cjs/agent/hook.d.ts +38 -0
  5. package/dist/cjs/agent/hook.js +175 -0
  6. package/dist/cjs/agent/registration.d.ts +10 -0
  7. package/dist/cjs/agent/registration.js +28 -0
  8. package/dist/cjs/agent/setup.d.ts +21 -0
  9. package/dist/cjs/agent/setup.js +229 -0
  10. package/dist/cjs/cli.js +88 -0
  11. package/dist/cjs/config/constants.d.ts +2 -0
  12. package/dist/cjs/config/constants.js +5 -1
  13. package/dist/cjs/config/pr-checkmate.template.json +10 -0
  14. package/dist/cjs/core/checks/findings.js +33 -7
  15. package/dist/cjs/core/checks/git/diff-smell.js +3 -1
  16. package/dist/cjs/core/checks/git/large-files.d.ts +1 -0
  17. package/dist/cjs/core/checks/git/large-files.js +3 -3
  18. package/dist/cjs/core/checks/languages/lint.js +27 -0
  19. package/dist/cjs/core/checks/languages/locate.d.ts +7 -0
  20. package/dist/cjs/core/checks/languages/locate.js +68 -0
  21. package/dist/cjs/core/checks/languages/prettier.js +15 -2
  22. package/dist/cjs/core/checks/languages/typecheck.js +4 -1
  23. package/dist/cjs/core/checks/pr/pr-size-check.d.ts +2 -0
  24. package/dist/cjs/core/checks/pr/pr-size-check.js +5 -5
  25. package/dist/cjs/core/checks/security/agent-instructions.d.ts +4 -0
  26. package/dist/cjs/core/checks/security/agent-instructions.js +149 -0
  27. package/dist/cjs/core/checks/security/diff-security.d.ts +7 -0
  28. package/dist/cjs/core/checks/security/diff-security.js +21 -1
  29. package/dist/cjs/core/checks/security/security.d.ts +0 -13
  30. package/dist/cjs/core/checks/security/security.js +27 -0
  31. package/dist/cjs/core/checks/security/workflow-security.js +33 -0
  32. package/dist/cjs/core/commands.d.ts +6 -0
  33. package/dist/cjs/core/commands.js +11 -1
  34. package/dist/cjs/core/finding-store.d.ts +16 -0
  35. package/dist/cjs/core/finding-store.js +73 -0
  36. package/dist/cjs/core/registry.js +2 -0
  37. package/dist/cjs/core/reporters.js +9 -0
  38. package/dist/cjs/core/run-checks.js +15 -5
  39. package/dist/cjs/core/sarif.d.ts +15 -0
  40. package/dist/cjs/core/sarif.js +60 -0
  41. package/dist/cjs/core/types.d.ts +7 -2
  42. package/dist/cjs/index.d.ts +2 -1
  43. package/dist/cjs/index.js +4 -1
  44. package/dist/cjs/init.js +11 -0
  45. package/dist/cjs/interfaces/index.d.ts +12 -0
  46. package/dist/cjs/mcp/config-tools.d.ts +30 -0
  47. package/dist/cjs/mcp/config-tools.js +320 -0
  48. package/dist/cjs/mcp/dependency.d.ts +34 -0
  49. package/dist/cjs/mcp/dependency.js +413 -0
  50. package/dist/cjs/mcp/protocol.d.ts +91 -0
  51. package/dist/cjs/mcp/protocol.js +181 -0
  52. package/dist/cjs/mcp/review.d.ts +64 -0
  53. package/dist/cjs/mcp/review.js +150 -0
  54. package/dist/cjs/mcp/serve.d.ts +8 -0
  55. package/dist/cjs/mcp/serve.js +49 -0
  56. package/dist/cjs/mcp/settings.d.ts +13 -0
  57. package/dist/cjs/mcp/settings.js +50 -0
  58. package/dist/cjs/mcp/tools.d.ts +23 -0
  59. package/dist/cjs/mcp/tools.js +618 -0
  60. package/dist/cjs/utils/execa.d.ts +7 -0
  61. package/dist/cjs/utils/execa.js +41 -1
  62. package/dist/cjs/utils/result-collector.d.ts +17 -1
  63. package/dist/cjs/utils/result-collector.js +7 -2
  64. package/dist/esm/agent/hook.d.ts +38 -0
  65. package/dist/esm/agent/hook.js +167 -0
  66. package/dist/esm/agent/registration.d.ts +10 -0
  67. package/dist/esm/agent/registration.js +21 -0
  68. package/dist/esm/agent/setup.d.ts +21 -0
  69. package/dist/esm/agent/setup.js +220 -0
  70. package/dist/esm/cli.js +86 -1
  71. package/dist/esm/config/constants.d.ts +2 -0
  72. package/dist/esm/config/constants.js +4 -0
  73. package/dist/esm/config/pr-checkmate.template.json +10 -0
  74. package/dist/esm/core/checks/findings.js +33 -7
  75. package/dist/esm/core/checks/git/diff-smell.js +3 -1
  76. package/dist/esm/core/checks/git/large-files.d.ts +1 -0
  77. package/dist/esm/core/checks/git/large-files.js +1 -1
  78. package/dist/esm/core/checks/languages/lint.js +28 -1
  79. package/dist/esm/core/checks/languages/locate.d.ts +7 -0
  80. package/dist/esm/core/checks/languages/locate.js +60 -0
  81. package/dist/esm/core/checks/languages/prettier.js +15 -2
  82. package/dist/esm/core/checks/languages/typecheck.js +4 -1
  83. package/dist/esm/core/checks/pr/pr-size-check.d.ts +2 -0
  84. package/dist/esm/core/checks/pr/pr-size-check.js +2 -2
  85. package/dist/esm/core/checks/security/agent-instructions.d.ts +4 -0
  86. package/dist/esm/core/checks/security/agent-instructions.js +146 -0
  87. package/dist/esm/core/checks/security/diff-security.d.ts +7 -0
  88. package/dist/esm/core/checks/security/diff-security.js +20 -0
  89. package/dist/esm/core/checks/security/security.d.ts +0 -13
  90. package/dist/esm/core/checks/security/security.js +27 -0
  91. package/dist/esm/core/checks/security/workflow-security.js +33 -0
  92. package/dist/esm/core/commands.d.ts +6 -0
  93. package/dist/esm/core/commands.js +10 -0
  94. package/dist/esm/core/finding-store.d.ts +16 -0
  95. package/dist/esm/core/finding-store.js +67 -0
  96. package/dist/esm/core/registry.js +2 -0
  97. package/dist/esm/core/reporters.js +9 -0
  98. package/dist/esm/core/run-checks.js +15 -5
  99. package/dist/esm/core/sarif.d.ts +15 -0
  100. package/dist/esm/core/sarif.js +57 -0
  101. package/dist/esm/core/types.d.ts +7 -2
  102. package/dist/esm/index.d.ts +2 -1
  103. package/dist/esm/index.js +2 -0
  104. package/dist/esm/init.js +12 -1
  105. package/dist/esm/interfaces/index.d.ts +12 -0
  106. package/dist/esm/mcp/config-tools.d.ts +30 -0
  107. package/dist/esm/mcp/config-tools.js +310 -0
  108. package/dist/esm/mcp/dependency.d.ts +34 -0
  109. package/dist/esm/mcp/dependency.js +408 -0
  110. package/dist/esm/mcp/protocol.d.ts +91 -0
  111. package/dist/esm/mcp/protocol.js +175 -0
  112. package/dist/esm/mcp/review.d.ts +64 -0
  113. package/dist/esm/mcp/review.js +139 -0
  114. package/dist/esm/mcp/serve.d.ts +8 -0
  115. package/dist/esm/mcp/serve.js +43 -0
  116. package/dist/esm/mcp/settings.d.ts +13 -0
  117. package/dist/esm/mcp/settings.js +43 -0
  118. package/dist/esm/mcp/tools.d.ts +23 -0
  119. package/dist/esm/mcp/tools.js +611 -0
  120. package/dist/esm/utils/execa.d.ts +7 -0
  121. package/dist/esm/utils/execa.js +40 -1
  122. package/dist/esm/utils/result-collector.d.ts +17 -1
  123. package/dist/esm/utils/result-collector.js +7 -2
  124. package/package.json +7 -3
  125. package/pr-checkmate.schema.json +35 -0
  126. package/src/config/cspell.json +1 -0
  127. package/src/config/pr-checkmate.schema.json +35 -0
package/dist/esm/cli.js CHANGED
@@ -1,11 +1,20 @@
1
1
  #!/usr/bin/env node
2
+ import fs from 'node:fs';
3
+ import path from 'node:path';
4
+ import { evaluateHook } from './agent/hook.js';
5
+ import { reportSetup, setupAgent } from './agent/setup.js';
2
6
  import { loadProjectConfig } from './config/loader.js';
3
- import { COMMAND_TO_CHECK, FLAGS, STANDALONE_COMMANDS, TOOLING_COMMANDS } from './core/commands.js';
7
+ import { AGENT_COMMANDS, COMMAND_TO_CHECK, FLAGS, STANDALONE_COMMANDS, TOOLING_COMMANDS, } from './core/commands.js';
4
8
  import { runChecks } from './core/index.js';
5
9
  import { installProfiles, pruneCache, runDoctor } from './core/install/doctor.js';
6
10
  import { ensureGrypeDb } from './core/install/grype-db.js';
11
+ import { toSarif } from './core/sarif.js';
7
12
  import { init } from './init.js';
13
+ import { serve } from './mcp/serve.js';
14
+ import { createServerDefinition } from './mcp/tools.js';
15
+ import { isolateInheritedStdio } from './utils/execa.js';
8
16
  import { getUpdateNotice, logger } from './utils/index.js';
17
+ import { packageVersion } from './utils/package-version.js';
9
18
  const argv = process.argv.slice(2);
10
19
  /**
11
20
  * Flags are separated from positional arguments so they compose with every command
@@ -52,6 +61,28 @@ function rejectConflictingScope() {
52
61
  logger.error('[cli]: "--all" applies only to "install". Did you mean "--full"?');
53
62
  process.exit(1);
54
63
  }
64
+ // `mcp` speaks a protocol on stdout and `hook` is invoked by a harness with a
65
+ // fixed payload: neither has anything to configure from the command line, and a
66
+ // flag that quietly did nothing would look like it had.
67
+ if ((cmd === 'mcp' || cmd === 'hook') && flags.length > 0) {
68
+ logger.error(`[cli]: "${cmd}" takes no flags, got: ${flags.join(', ')}.`);
69
+ process.exit(1);
70
+ }
71
+ // Only a command that runs checks has findings to export; `all`, `precommit` and a
72
+ // named check do, every other standalone command does not.
73
+ const runsChecks = !cmd || cmd === 'all' || cmd === 'precommit' || !STANDALONE_COMMANDS.includes(cmd);
74
+ if (flags.includes('--sarif') && !runsChecks) {
75
+ logger.error('[cli]: "--sarif" applies only to commands that run checks.');
76
+ process.exit(1);
77
+ }
78
+ if (flags.includes('--no-hook') && cmd !== 'agent-setup') {
79
+ logger.error('[cli]: "--no-hook" applies only to "agent-setup".');
80
+ process.exit(1);
81
+ }
82
+ if (flags.includes('--full') && AGENT_COMMANDS.includes(cmd ?? '')) {
83
+ logger.error(`[cli]: "${cmd}" reviews nothing on its own, so "--full" has no meaning.`);
84
+ process.exit(1);
85
+ }
55
86
  if (flags.includes('--full') && TOOLING_COMMANDS.includes(cmd ?? '')) {
56
87
  logger.error(`[cli]: "${cmd}" manages tooling and reviews nothing, so "--full" has no meaning.`);
57
88
  process.exit(1);
@@ -73,6 +104,55 @@ function rejectExtraArgs() {
73
104
  logger.error(`[cli]: "${cmd}" takes no other arguments, got: ${args.slice(1).join(', ')}. Run them as a separate command.`);
74
105
  process.exit(1);
75
106
  }
107
+ /**
108
+ * Write the report as SARIF when `--sarif` was passed. Written before the exit code
109
+ * is decided, so a failing run still leaves the file a dashboard needs to show why.
110
+ */
111
+ function writeSarifIfRequested(report) {
112
+ if (!flags.includes('--sarif'))
113
+ return;
114
+ const file = path.resolve(process.cwd(), 'pr-checkmate.sarif');
115
+ fs.writeFileSync(file, `${JSON.stringify(toSarif(report, packageVersion()), null, 2)}\n`);
116
+ logger.info(`[sarif]: wrote ${file}`);
117
+ }
118
+ /** Everything the harness wrote to stdin, as text; empty when stdin is closed or a terminal. */
119
+ async function readStdin() {
120
+ if (process.stdin.isTTY)
121
+ return '';
122
+ const chunks = [];
123
+ for await (const chunk of process.stdin)
124
+ chunks.push(Buffer.from(chunk));
125
+ return Buffer.concat(chunks).toString('utf-8');
126
+ }
127
+ /**
128
+ * The commands that serve AI agents. Returns whether `cmd` was one of them (and has
129
+ * therefore already exited); kept out of the main dispatcher so that one stays
130
+ * readable as the list of commands grows.
131
+ *
132
+ * `mcp` must stay ahead of anything that could print: from here until stdin closes,
133
+ * stdout carries protocol messages and nothing else.
134
+ */
135
+ async function runAgentCommand() {
136
+ if (cmd === 'mcp') {
137
+ await serve(createServerDefinition());
138
+ process.exit(0);
139
+ }
140
+ if (cmd === 'hook') {
141
+ // Discarded rather than shown: the harness reads stdout and stderr of a hook
142
+ // as instructions to the model, so only the verdict may reach either.
143
+ isolateInheritedStdio('discard');
144
+ logger.setSink({ out: () => undefined, err: () => undefined });
145
+ const verdict = await evaluateHook(await readStdin(), process.cwd());
146
+ if (verdict.stderr)
147
+ process.stderr.write(`${verdict.stderr}\n`);
148
+ process.exit(verdict.exitCode);
149
+ }
150
+ if (cmd === 'agent-setup') {
151
+ reportSetup(setupAgent(process.cwd(), { hook: !flags.includes('--no-hook') }));
152
+ process.exit(0);
153
+ }
154
+ return false;
155
+ }
76
156
  void (async () => {
77
157
  try {
78
158
  rejectUnknownFlags();
@@ -82,6 +162,8 @@ void (async () => {
82
162
  await init();
83
163
  process.exit(0);
84
164
  }
165
+ if (await runAgentCommand())
166
+ return;
85
167
  // Tooling management. These run no checks — they prepare, inspect or clean
86
168
  // up what the checks need, so they never touch the diff or the reporter.
87
169
  if (cmd === 'install') {
@@ -123,12 +205,14 @@ void (async () => {
123
205
  logger.info('');
124
206
  notice.forEach(line => logger.info(line));
125
207
  }
208
+ writeSarifIfRequested(report);
126
209
  process.exit(report.ok ? 0 : 1);
127
210
  }
128
211
  // Local pre-commit: check the staged changes (index vs HEAD), print to
129
212
  // stdout, never modify files. Exits non-zero on failure to block the commit.
130
213
  if (cmd === 'precommit') {
131
214
  const report = await runChecks({ staged: true, reporter: 'stdout', write: false });
215
+ writeSarifIfRequested(report);
132
216
  process.exit(report.ok ? 0 : 1);
133
217
  }
134
218
  // Every remaining argument is a check name, so `pr-checkmate lint spellcheck`
@@ -141,6 +225,7 @@ void (async () => {
141
225
  }
142
226
  const checkNames = [...new Set(args.map(arg => COMMAND_TO_CHECK[arg]))];
143
227
  const report = await runChecks({ only: checkNames, reporter: 'stdout', write: true, full });
228
+ writeSarifIfRequested(report);
144
229
  process.exit(report.ok ? 0 : 1);
145
230
  }
146
231
  catch (err) {
@@ -95,6 +95,7 @@ export declare const SOURCE_EXTENSIONS: {
95
95
  json: string[];
96
96
  all: string[];
97
97
  };
98
+ export declare const AGENT_SETUP_COMMAND = "npx pr-checkmate agent-setup";
98
99
  export declare const DEFAULT_COMMANDS: {
99
100
  'npx pr-checkmate init': string;
100
101
  'npx pr-checkmate all': string;
@@ -109,6 +110,7 @@ export declare const DEFAULT_COMMANDS: {
109
110
  'npx pr-checkmate diff-smell': string;
110
111
  'npx pr-checkmate pr-body': string;
111
112
  'npx pr-checkmate duplicate': string;
113
+ "npx pr-checkmate agent-setup": string;
112
114
  };
113
115
  /**
114
116
  * Packages allow-listed for the license check by default.
@@ -225,6 +225,7 @@ export const SOURCE_EXTENSIONS = {
225
225
  json: ['.json'],
226
226
  all: ['.ts', '.tsx', '.js', '.jsx', '.json', '.md', '.mdx'],
227
227
  };
228
+ export const AGENT_SETUP_COMMAND = 'npx pr-checkmate agent-setup';
228
229
  export const DEFAULT_COMMANDS = {
229
230
  'npx pr-checkmate init': 'Create pr-checkmate.json and the CI workflow (first-run setup)',
230
231
  'npx pr-checkmate all': 'Run all checks over the changes — the PR diff in CI, your branch changes locally',
@@ -239,6 +240,7 @@ export const DEFAULT_COMMANDS = {
239
240
  'npx pr-checkmate diff-smell': 'Scan git diff for code smells',
240
241
  'npx pr-checkmate pr-body': 'Validate PR description',
241
242
  'npx pr-checkmate duplicate': 'Detect duplicate code blocks (jscpd)',
243
+ [AGENT_SETUP_COMMAND]: 'Connect your AI agent: MCP server, rules for it and edit hooks (writes .mcp.json)',
242
244
  };
243
245
  /**
244
246
  * Packages allow-listed for the license check by default.
@@ -320,6 +322,8 @@ export const KNOWN_CONFIG_KEYS = new Set([
320
322
  'diffSecurity',
321
323
  'workflowSecurity',
322
324
  'dockerfileSecurity',
325
+ 'agentInstructions',
326
+ 'mcp',
323
327
  'sensitiveFileGuard',
324
328
  'migrationSafety',
325
329
  // dependencies
@@ -97,6 +97,16 @@
97
97
  "enabled": true,
98
98
  "ignore": []
99
99
  },
100
+ "agentInstructions": {
101
+ "enabled": true,
102
+ "ignore": []
103
+ },
104
+ "//mcp": "What the MCP server offers an AI agent here. 'enabled': false turns it off; 'disabledTools' hides tools by name; 'readOnly' hides the ones that write files. Applies from the agent's next request.",
105
+ "mcp": {
106
+ "enabled": true,
107
+ "disabledTools": [],
108
+ "readOnly": false
109
+ },
100
110
  "//sensitiveFileGuard": "Flags .env files, private keys, CI config and lockfiles. 'ignorePaths' excuses ONE file by glob (a .pem test fixture); 'ignore' silences a whole CATEGORY and would excuse the next real key too — reach for ignorePaths first.",
101
111
  "sensitiveFileGuard": {
102
112
  "enabled": true,
@@ -2,6 +2,7 @@ import fs from 'node:fs';
2
2
  import path from 'node:path';
3
3
  import { execa } from '../../utils/execa.js';
4
4
  import { logger, matchesAnyGlob } from '../../utils/index.js';
5
+ import { fileFindings, noteLocation } from '../finding-store.js';
5
6
  import { listTrackedFiles } from '../targets.js';
6
7
  import { fail, pass, warn } from '../types.js';
7
8
  /**
@@ -370,6 +371,8 @@ export const DEFAULT_DATAFLOW_WINDOW = 10;
370
371
  const CROSS_LINE_SQL_LABEL = 'Interpolated value reaches a query (SQL injection risk, cross-line)';
371
372
  /** `@@ ... @@` — a new hunk, and the boundary taint never crosses. */
372
373
  const DIFF_HUNK_HEADER = /^@@ /;
374
+ /** The first line of the new side of a hunk: `@@ -3,2 +10,4 @@` → 10. */
375
+ const HUNK_NEW_START = /^@@ -\d+(?:,\d+)? \+(\d+)/;
373
376
  /**
374
377
  * Whether this line hands `name` to a query sink.
375
378
  *
@@ -443,6 +446,9 @@ export function scanDiffPatterns(stdout, patterns, opts = {}) {
443
446
  const mode = opts.comments ?? 'language';
444
447
  const ignorePaths = opts.ignorePaths ?? [];
445
448
  let syntax = 'both';
449
+ // Where the walk is, for findings that need to say so.
450
+ let file = '';
451
+ let newLine = 0;
446
452
  // Block comments span lines, so the state belongs to the walk, not to one line.
447
453
  let inBlockComment = false;
448
454
  // Whole files can be excluded by glob; the flag persists until the next header.
@@ -453,6 +459,7 @@ export function scanDiffPatterns(stdout, patterns, opts = {}) {
453
459
  for (const line of stdout.split('\n')) {
454
460
  const header = DIFF_FILE_HEADER.exec(line);
455
461
  if (header) {
462
+ file = header[1];
456
463
  syntax = mode === 'language' ? commentSyntaxFor(header[1]) : 'both';
457
464
  inBlockComment = false;
458
465
  skippingFile = ignorePaths.length > 0 && matchesAnyGlob(header[1], ignorePaths);
@@ -461,9 +468,15 @@ export function scanDiffPatterns(stdout, patterns, opts = {}) {
461
468
  }
462
469
  // Checked before the `+` filter below, which a hunk header does not satisfy.
463
470
  if (DIFF_HUNK_HEADER.test(line)) {
471
+ newLine = Number(HUNK_NEW_START.exec(line)?.[1] ?? 0);
464
472
  taint.reset();
465
473
  continue;
466
474
  }
475
+ // Counted before any skip: an ignored or excluded line still occupies a line
476
+ // number in the file, and the ones after it must not shift.
477
+ const lineNo = newLine;
478
+ if (line.startsWith('+'))
479
+ newLine++;
467
480
  if (skippingFile)
468
481
  continue;
469
482
  // Only added lines carry block-comment state: a `-` line is code being
@@ -475,18 +488,28 @@ export function scanDiffPatterns(stdout, patterns, opts = {}) {
475
488
  const prepared = uncomment(line, { mode, syntax, inBlockComment });
476
489
  inBlockComment = prepared.inBlockComment;
477
490
  const asCode = stripStringLiterals(prepared.text);
478
- for (const { pattern, label, severity, view } of patterns) {
479
- if (pattern.test(view === 'code' ? asCode : prepared.text)) {
480
- const bucket = severity === 'error' ? errors : warnings;
481
- (bucket[label] ?? (bucket[label] = [])).push(line.slice(1).trim().substring(0, SAMPLE_MAX_LENGTH));
482
- }
483
- }
491
+ const where = { file, line: lineNo };
492
+ recordMatches(patterns, { text: prepared.text, asCode }, line, where, { errors, warnings });
484
493
  if (taint.inspect(prepared.text, asCode)) {
485
- (warnings[CROSS_LINE_SQL_LABEL] ?? (warnings[CROSS_LINE_SQL_LABEL] = [])).push(line.slice(1).trim().substring(0, SAMPLE_MAX_LENGTH));
494
+ record(warnings, CROSS_LINE_SQL_LABEL, line, where);
486
495
  }
487
496
  }
488
497
  return { errors, warnings };
489
498
  }
499
+ /** File one added line under `label` and remember where it was, for findings that say so. */
500
+ function record(bucket, label, line, where) {
501
+ const sample = line.slice(1).trim().substring(0, SAMPLE_MAX_LENGTH);
502
+ (bucket[label] ?? (bucket[label] = [])).push(sample);
503
+ noteLocation(label, sample, where.file, where.line);
504
+ }
505
+ /** File every pattern that matches one prepared line under its own label and severity. */
506
+ function recordMatches(patterns, view, line, where, into) {
507
+ for (const { pattern, label, severity, view: wants } of patterns) {
508
+ if (pattern.test(wants === 'code' ? view.asCode : view.text)) {
509
+ record(severity === 'error' ? into.errors : into.warnings, label, line, where);
510
+ }
511
+ }
512
+ }
490
513
  /**
491
514
  * Reduce one added line to what should be matched against: block comments
492
515
  * blanked (carrying the open state on), then the trailing line comment removed.
@@ -577,6 +600,7 @@ export function bucketTotal(bucket) {
577
600
  */
578
601
  export function reportCountedFindings(findings, ctx, opts) {
579
602
  const sev = severityEmitter(opts.severity, opts.fallback ?? 'warn');
603
+ fileFindings(findings, sev.icon === '❌' ? 'error' : 'warn');
580
604
  logFindings(findings, {
581
605
  prefix: opts.prefix,
582
606
  sampleLimit: opts.sampleLimit ?? ctx.config.log?.sampleLimit ?? 3,
@@ -681,6 +705,8 @@ export function reportSeverityBuckets(errorsIn, warningsIn, opts) {
681
705
  const ignore = opts.ignore ?? [];
682
706
  const filed = applyOverrides(dropIgnored(errorsIn, ignore), dropIgnored(warningsIn, ignore), opts.severityOverrides ?? {});
683
707
  const { errors, warnings } = filed;
708
+ fileFindings(errors, 'error');
709
+ fileFindings(warnings, 'warn');
684
710
  const totalErrors = bucketTotal(errors);
685
711
  const totalWarnings = bucketTotal(warnings);
686
712
  if (totalErrors === 0 && totalWarnings === 0)
@@ -19,7 +19,9 @@ export const CODE_SMELLS = [
19
19
  view: 'code',
20
20
  },
21
21
  {
22
- pattern: /^\+(?!\+).*\bdebugger\b/,
22
+ // A statement, not a mention: `debugger` ends the line or follows a `;`, `{`, `}` or `)`.
23
+ // A regex literal (`/debugger/`) or an object key (`{ debugger: 1 }`) is not one.
24
+ pattern: /^\+(?!\+)(?:.*[;{})]|\s*)\s*debugger\b\s*;?\s*$/,
23
25
  label: 'debugger statement',
24
26
  severity: 'warn',
25
27
  view: 'code',
@@ -1,2 +1,3 @@
1
1
  import { Check } from '../../types.js';
2
+ export declare const DEFAULT_MAX_KB = 500;
2
3
  export declare const largeFilesCheck: Check;
@@ -5,7 +5,7 @@ import { logger, matchesAnyGlob } from '../../../utils/index.js';
5
5
  import { resolveTargetFiles } from '../../targets.js';
6
6
  import { pass, skip } from '../../types.js';
7
7
  import { severityEmitter } from '../findings.js';
8
- const DEFAULT_MAX_KB = 500;
8
+ export const DEFAULT_MAX_KB = 500;
9
9
  /**
10
10
  * Lockfiles are legitimately large and always generated, never accidental — so
11
11
  * they're exempt from the size/binary guard by default (a 600 KB
@@ -1,10 +1,15 @@
1
+ import fs from 'node:fs';
2
+ import os from 'node:os';
1
3
  import path from 'node:path';
2
4
  import { getPackageConfigPath, getSourcePaths, hasLocalConfig, IGNORE_PATTERNS, } from '../../../config/index.js';
3
5
  import { execa } from '../../../utils/execa.js';
4
- import { logger, registeredToolPaths, resolvePackageBin } from '../../../utils/index.js';
6
+ import { cleanupTempFile, logger, registeredToolPaths, resolvePackageBin, } from '../../../utils/index.js';
7
+ import { addFinding } from '../../finding-store.js';
5
8
  import { clientToolPaths } from '../../install/reuse.js';
6
9
  import { resolveScopedTargetFiles } from '../../targets.js';
7
10
  import { fail, pass, skip, warn } from '../../types.js';
11
+ import { parseEslintJson } from './locate.js';
12
+ const MAX_LOGGED_PROBLEMS = 50;
8
13
  /**
9
14
  * Resolve the ESLint binary under the client's `install.reuseLocal` policy.
10
15
  *
@@ -30,6 +35,17 @@ async function getESLintMajorVersion(eslintBin) {
30
35
  return 8;
31
36
  }
32
37
  }
38
+ function readProblems(reportFile, cwd) {
39
+ try {
40
+ return parseEslintJson(fs.readFileSync(reportFile, 'utf-8'), cwd);
41
+ }
42
+ catch {
43
+ return [];
44
+ }
45
+ finally {
46
+ cleanupTempFile(reportFile);
47
+ }
48
+ }
33
49
  export const lintCheck = {
34
50
  name: 'ESLint',
35
51
  phase: 'blocking',
@@ -81,12 +97,23 @@ export const lintCheck = {
81
97
  if (!hasLocal && version < 9 && toolRoots.length > 0) {
82
98
  args.push('--resolve-plugins-relative-to', toolRoots[0]);
83
99
  }
100
+ // JSON to a file, not stylish text to the terminal: the file is what lets a
101
+ // finding name its file, line and rule instead of saying "lint errors found".
102
+ // The same problems are logged below in a compact form, so nothing is lost.
103
+ const reportFile = path.join(os.tmpdir(), `pr-checkmate-eslint-${process.pid}-${Date.now()}.json`);
104
+ args.push('--format', 'json', '--output-file', reportFile);
84
105
  const result = await execa(process.execPath, [eslintBin, ...args], {
85
106
  cwd: ctx.cwd,
86
107
  stdio: 'inherit',
87
108
  reject: false,
88
109
  env: { PR_CHECKMATE_TOOL_ROOTS: toolRoots.join(path.delimiter) },
89
110
  });
111
+ const problems = readProblems(reportFile, ctx.cwd);
112
+ problems.slice(0, MAX_LOGGED_PROBLEMS).forEach(f => {
113
+ logger.warn(`[ESLint]: ${f.file}:${f.line ?? 0} ${f.rule} ${f.snippet ?? ''}`);
114
+ });
115
+ if (result.exitCode === 1)
116
+ problems.forEach(addFinding);
90
117
  if (result.exitCode === 0)
91
118
  return pass();
92
119
  // ESLint exits 1 for lint errors and 2 for a fatal error — a config it cannot
@@ -0,0 +1,7 @@
1
+ import type { Finding } from '../../types.js';
2
+ /** `src/a.ts(3,5): error TS2322: Type …` lines of `tsc --pretty false`. */
3
+ export declare function parseTscDiagnostics(output: string): Finding[];
4
+ /** The array `eslint --format json` writes. Anything else yields no findings. */
5
+ export declare function parseEslintJson(raw: string, cwd: string): Finding[];
6
+ /** One path per line, as `prettier --list-different` prints them. */
7
+ export declare function parseListDifferent(stdout: string): Finding[];
@@ -0,0 +1,60 @@
1
+ /**
2
+ * Turn what the language tools print into located findings.
3
+ *
4
+ * The three tools disagree on how to say where a problem is, so each gets a small
5
+ * pure parser here and the checks only decide what to do with the result. Without
6
+ * these an agent was told "lint errors found" and nothing else.
7
+ */
8
+ import path from 'node:path';
9
+ const MAX_SNIPPET = 160;
10
+ const TSC_DIAGNOSTIC = /^(.+?)\((\d+),\d+\): error (TS\d+): (.*)$/;
11
+ const clip = (text) => text.length > MAX_SNIPPET ? `${text.slice(0, MAX_SNIPPET - 1)}…` : text;
12
+ /** `src/a.ts(3,5): error TS2322: Type …` lines of `tsc --pretty false`. */
13
+ export function parseTscDiagnostics(output) {
14
+ const found = [];
15
+ for (const line of output.split('\n')) {
16
+ const m = TSC_DIAGNOSTIC.exec(line.trim());
17
+ if (m) {
18
+ found.push({
19
+ file: m[1].replace(/\\/g, '/'),
20
+ line: Number(m[2]),
21
+ rule: m[3],
22
+ snippet: clip(m[4]),
23
+ severity: 'error',
24
+ });
25
+ }
26
+ }
27
+ return found;
28
+ }
29
+ /** The array `eslint --format json` writes. Anything else yields no findings. */
30
+ export function parseEslintJson(raw, cwd) {
31
+ let report;
32
+ try {
33
+ report = JSON.parse(raw);
34
+ }
35
+ catch {
36
+ return [];
37
+ }
38
+ if (!Array.isArray(report))
39
+ return [];
40
+ return report.flatMap(file => (file.messages ?? []).map(m => ({
41
+ file: path.relative(cwd, file.filePath).replace(/\\/g, '/'),
42
+ ...(m.line !== undefined && { line: m.line }),
43
+ rule: m.ruleId ?? 'parse-error',
44
+ snippet: clip(m.message),
45
+ severity: m.severity === 2 ? 'error' : 'warn',
46
+ })));
47
+ }
48
+ /** One path per line, as `prettier --list-different` prints them. */
49
+ export function parseListDifferent(stdout) {
50
+ return stdout
51
+ .split('\n')
52
+ .map(l => l.trim())
53
+ .filter(Boolean)
54
+ .map(file => ({
55
+ file: file.replace(/\\/g, '/'),
56
+ rule: 'prettier',
57
+ snippet: 'not formatted',
58
+ severity: 'warn',
59
+ }));
60
+ }
@@ -3,8 +3,10 @@ import path from 'node:path';
3
3
  import { getPackageConfigPath, getSourcePaths, hasLocalConfig, IGNORE_PATTERNS, } from '../../../config/index.js';
4
4
  import { execa } from '../../../utils/execa.js';
5
5
  import { cleanupTempFile, logger, resolvePackageBin } from '../../../utils/index.js';
6
+ import { addFinding } from '../../finding-store.js';
6
7
  import { resolveScopedTargetFiles } from '../../targets.js';
7
8
  import { pass, skip, warn } from '../../types.js';
9
+ import { parseListDifferent } from './locate.js';
8
10
  function loadUserPrettierConfig(cwd) {
9
11
  const configPath = path.join(cwd, 'pr-checkmate.json');
10
12
  if (!fs.existsSync(configPath))
@@ -53,7 +55,9 @@ export const prettierCheck = {
53
55
  ignorePath = tempIgnore = createTempIgnoreFile(ctx.cwd);
54
56
  const hasLocal = hasLocalConfig(['.prettierrc', '.prettierrc.json', '.prettierrc.js', 'prettier.config.js'], ctx.cwd);
55
57
  // write=true → format in place; write=false → report-only (`--check`, never mutates files).
56
- const mode = ctx.write ? '--write' : '--check';
58
+ // `--list-different` names the unformatted files on stdout, which is what lets a
59
+ // finding point at them; `--check` only says how many there are.
60
+ const mode = ctx.write ? '--write' : '--list-different';
57
61
  let tempConfig = null;
58
62
  let args;
59
63
  if (hasLocal) {
@@ -67,11 +71,20 @@ export const prettierCheck = {
67
71
  try {
68
72
  const result = await execa(process.execPath, [prettierBin, ...args], {
69
73
  cwd: ctx.cwd,
70
- stdio: 'inherit',
74
+ ...(ctx.write && { stdio: 'inherit' }),
71
75
  reject: false,
72
76
  });
73
77
  if (result.exitCode === 0)
74
78
  return pass();
79
+ if (!ctx.write) {
80
+ const unformatted = parseListDifferent(String(result.stdout ?? ''));
81
+ unformatted.forEach(f => {
82
+ logger.warn(`[Prettier]: not formatted: ${f.file}`);
83
+ addFinding(f);
84
+ });
85
+ if (result.stderr)
86
+ logger.warn(String(result.stderr));
87
+ }
75
88
  // In --check mode a non-zero exit means "some files are not formatted".
76
89
  return warn(ctx.write ? 'prettier failed' : 'unformatted files (run with write to fix)');
77
90
  }
@@ -2,8 +2,10 @@ import fs from 'node:fs';
2
2
  import path from 'node:path';
3
3
  import { execa } from '../../../utils/execa.js';
4
4
  import { logger, resolvePackageBin } from '../../../utils/index.js';
5
+ import { addFinding } from '../../finding-store.js';
5
6
  import { clientToolPaths } from '../../install/reuse.js';
6
7
  import { fail, pass, skip, warn } from '../../types.js';
8
+ import { parseTscDiagnostics } from './locate.js';
7
9
  /**
8
10
  * Prefer the consumer project's own TypeScript so its tsconfig is compiled by the
9
11
  * version it was written for; fall back to the compiler bundled with pr-checkmate.
@@ -39,7 +41,7 @@ export const typecheckCheck = {
39
41
  return skip('project dependencies not installed (no node_modules) — run `npm ci` before typecheck');
40
42
  }
41
43
  const tscBin = resolveTsc(ctx);
42
- const result = await execa(process.execPath, [tscBin, '--noEmit'], {
44
+ const result = await execa(process.execPath, [tscBin, '--noEmit', '--pretty', 'false'], {
43
45
  cwd: ctx.cwd,
44
46
  reject: false,
45
47
  });
@@ -56,6 +58,7 @@ export const typecheckCheck = {
56
58
  logger.warn(`[TypeScript]: ⚠️ tsc exited ${result.exitCode ?? 'abnormally'} without reporting a type error — treating as a tooling failure, not a type error`);
57
59
  return warn(`tsc failed to run (exit ${result.exitCode ?? 'killed'})`);
58
60
  }
61
+ parseTscDiagnostics(output).forEach(addFinding);
59
62
  return fail(`${errorCount} type error(s)`);
60
63
  },
61
64
  };
@@ -1,2 +1,4 @@
1
1
  import { Check } from '../../types.js';
2
+ export declare const DEFAULT_MAX_FILES = 50;
3
+ export declare const DEFAULT_MAX_LINES = 1000;
2
4
  export declare const prSizeCheck: Check;
@@ -1,8 +1,8 @@
1
1
  import { execa } from '../../../utils/execa.js';
2
2
  import { logger } from '../../../utils/index.js';
3
3
  import { pass, skip, warn } from '../../types.js';
4
- const DEFAULT_MAX_FILES = 50;
5
- const DEFAULT_MAX_LINES = 1000;
4
+ export const DEFAULT_MAX_FILES = 50;
5
+ export const DEFAULT_MAX_LINES = 1000;
6
6
  export const prSizeCheck = {
7
7
  name: 'PR Size',
8
8
  phase: 'informational',
@@ -0,0 +1,4 @@
1
+ import { Check } from '../../types.js';
2
+ import { DiffPattern } from '../findings.js';
3
+ export declare const AGENT_PATTERNS: DiffPattern[];
4
+ export declare const agentInstructionsCheck: Check;