pr-checkmate 3.3.0 → 4.0.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.
Files changed (113) hide show
  1. package/LICENSE +8 -3
  2. package/README.md +53 -4
  3. package/dist/cjs/agent/hook.d.ts +37 -0
  4. package/dist/cjs/agent/hook.js +175 -0
  5. package/dist/cjs/agent/registration.d.ts +10 -0
  6. package/dist/cjs/agent/registration.js +28 -0
  7. package/dist/cjs/agent/setup.d.ts +20 -0
  8. package/dist/cjs/agent/setup.js +229 -0
  9. package/dist/cjs/cli.js +88 -0
  10. package/dist/cjs/config/constants.d.ts +2 -0
  11. package/dist/cjs/config/constants.js +5 -1
  12. package/dist/cjs/config/pr-checkmate.template.json +10 -0
  13. package/dist/cjs/core/checks/findings.js +33 -7
  14. package/dist/cjs/core/checks/git/large-files.d.ts +1 -0
  15. package/dist/cjs/core/checks/git/large-files.js +3 -3
  16. package/dist/cjs/core/checks/pr/pr-size-check.d.ts +2 -0
  17. package/dist/cjs/core/checks/pr/pr-size-check.js +5 -5
  18. package/dist/cjs/core/checks/security/agent-instructions.d.ts +4 -0
  19. package/dist/cjs/core/checks/security/agent-instructions.js +149 -0
  20. package/dist/cjs/core/checks/security/diff-security.d.ts +7 -0
  21. package/dist/cjs/core/checks/security/diff-security.js +21 -1
  22. package/dist/cjs/core/checks/security/security.d.ts +0 -13
  23. package/dist/cjs/core/checks/security/security.js +27 -0
  24. package/dist/cjs/core/checks/security/workflow-security.js +33 -0
  25. package/dist/cjs/core/commands.d.ts +6 -0
  26. package/dist/cjs/core/commands.js +11 -1
  27. package/dist/cjs/core/finding-store.d.ts +16 -0
  28. package/dist/cjs/core/finding-store.js +73 -0
  29. package/dist/cjs/core/registry.js +2 -0
  30. package/dist/cjs/core/reporters.js +9 -0
  31. package/dist/cjs/core/run-checks.js +15 -5
  32. package/dist/cjs/core/sarif.d.ts +13 -0
  33. package/dist/cjs/core/sarif.js +60 -0
  34. package/dist/cjs/core/types.d.ts +7 -2
  35. package/dist/cjs/index.d.ts +2 -1
  36. package/dist/cjs/index.js +4 -1
  37. package/dist/cjs/init.js +11 -0
  38. package/dist/cjs/interfaces/index.d.ts +12 -0
  39. package/dist/cjs/mcp/config-tools.d.ts +30 -0
  40. package/dist/cjs/mcp/config-tools.js +320 -0
  41. package/dist/cjs/mcp/dependency.d.ts +33 -0
  42. package/dist/cjs/mcp/dependency.js +407 -0
  43. package/dist/cjs/mcp/protocol.d.ts +97 -0
  44. package/dist/cjs/mcp/protocol.js +181 -0
  45. package/dist/cjs/mcp/review.d.ts +63 -0
  46. package/dist/cjs/mcp/review.js +150 -0
  47. package/dist/cjs/mcp/serve.d.ts +8 -0
  48. package/dist/cjs/mcp/serve.js +49 -0
  49. package/dist/cjs/mcp/settings.d.ts +13 -0
  50. package/dist/cjs/mcp/settings.js +50 -0
  51. package/dist/cjs/mcp/tools.d.ts +23 -0
  52. package/dist/cjs/mcp/tools.js +633 -0
  53. package/dist/cjs/utils/execa.d.ts +7 -0
  54. package/dist/cjs/utils/execa.js +41 -1
  55. package/dist/cjs/utils/result-collector.d.ts +17 -1
  56. package/dist/cjs/utils/result-collector.js +7 -2
  57. package/dist/esm/agent/hook.d.ts +37 -0
  58. package/dist/esm/agent/hook.js +167 -0
  59. package/dist/esm/agent/registration.d.ts +10 -0
  60. package/dist/esm/agent/registration.js +21 -0
  61. package/dist/esm/agent/setup.d.ts +20 -0
  62. package/dist/esm/agent/setup.js +220 -0
  63. package/dist/esm/cli.js +86 -1
  64. package/dist/esm/config/constants.d.ts +2 -0
  65. package/dist/esm/config/constants.js +4 -0
  66. package/dist/esm/config/pr-checkmate.template.json +10 -0
  67. package/dist/esm/core/checks/findings.js +33 -7
  68. package/dist/esm/core/checks/git/large-files.d.ts +1 -0
  69. package/dist/esm/core/checks/git/large-files.js +1 -1
  70. package/dist/esm/core/checks/pr/pr-size-check.d.ts +2 -0
  71. package/dist/esm/core/checks/pr/pr-size-check.js +2 -2
  72. package/dist/esm/core/checks/security/agent-instructions.d.ts +4 -0
  73. package/dist/esm/core/checks/security/agent-instructions.js +146 -0
  74. package/dist/esm/core/checks/security/diff-security.d.ts +7 -0
  75. package/dist/esm/core/checks/security/diff-security.js +20 -0
  76. package/dist/esm/core/checks/security/security.d.ts +0 -13
  77. package/dist/esm/core/checks/security/security.js +27 -0
  78. package/dist/esm/core/checks/security/workflow-security.js +33 -0
  79. package/dist/esm/core/commands.d.ts +6 -0
  80. package/dist/esm/core/commands.js +10 -0
  81. package/dist/esm/core/finding-store.d.ts +16 -0
  82. package/dist/esm/core/finding-store.js +67 -0
  83. package/dist/esm/core/registry.js +2 -0
  84. package/dist/esm/core/reporters.js +9 -0
  85. package/dist/esm/core/run-checks.js +15 -5
  86. package/dist/esm/core/sarif.d.ts +13 -0
  87. package/dist/esm/core/sarif.js +57 -0
  88. package/dist/esm/core/types.d.ts +7 -2
  89. package/dist/esm/index.d.ts +2 -1
  90. package/dist/esm/index.js +2 -0
  91. package/dist/esm/init.js +12 -1
  92. package/dist/esm/interfaces/index.d.ts +12 -0
  93. package/dist/esm/mcp/config-tools.d.ts +30 -0
  94. package/dist/esm/mcp/config-tools.js +310 -0
  95. package/dist/esm/mcp/dependency.d.ts +33 -0
  96. package/dist/esm/mcp/dependency.js +402 -0
  97. package/dist/esm/mcp/protocol.d.ts +97 -0
  98. package/dist/esm/mcp/protocol.js +175 -0
  99. package/dist/esm/mcp/review.d.ts +63 -0
  100. package/dist/esm/mcp/review.js +139 -0
  101. package/dist/esm/mcp/serve.d.ts +8 -0
  102. package/dist/esm/mcp/serve.js +43 -0
  103. package/dist/esm/mcp/settings.d.ts +13 -0
  104. package/dist/esm/mcp/settings.js +43 -0
  105. package/dist/esm/mcp/tools.d.ts +23 -0
  106. package/dist/esm/mcp/tools.js +626 -0
  107. package/dist/esm/utils/execa.d.ts +7 -0
  108. package/dist/esm/utils/execa.js +40 -1
  109. package/dist/esm/utils/result-collector.d.ts +17 -1
  110. package/dist/esm/utils/result-collector.js +7 -2
  111. package/package.json +6 -2
  112. package/pr-checkmate.schema.json +35 -0
  113. package/src/config/pr-checkmate.schema.json +35 -0
package/dist/cjs/cli.js CHANGED
@@ -1,13 +1,25 @@
1
1
  #!/usr/bin/env node
2
2
  "use strict";
3
+ var __importDefault = (this && this.__importDefault) || function (mod) {
4
+ return (mod && mod.__esModule) ? mod : { "default": mod };
5
+ };
3
6
  Object.defineProperty(exports, "__esModule", { value: true });
7
+ const node_fs_1 = __importDefault(require("node:fs"));
8
+ const node_path_1 = __importDefault(require("node:path"));
9
+ const hook_js_1 = require("./agent/hook.js");
10
+ const setup_js_1 = require("./agent/setup.js");
4
11
  const loader_js_1 = require("./config/loader.js");
5
12
  const commands_js_1 = require("./core/commands.js");
6
13
  const index_js_1 = require("./core/index.js");
7
14
  const doctor_js_1 = require("./core/install/doctor.js");
8
15
  const grype_db_js_1 = require("./core/install/grype-db.js");
16
+ const sarif_js_1 = require("./core/sarif.js");
9
17
  const init_js_1 = require("./init.js");
18
+ const serve_js_1 = require("./mcp/serve.js");
19
+ const tools_js_1 = require("./mcp/tools.js");
20
+ const execa_js_1 = require("./utils/execa.js");
10
21
  const index_js_2 = require("./utils/index.js");
22
+ const package_version_js_1 = require("./utils/package-version.js");
11
23
  const argv = process.argv.slice(2);
12
24
  /**
13
25
  * Flags are separated from positional arguments so they compose with every command
@@ -54,6 +66,28 @@ function rejectConflictingScope() {
54
66
  index_js_2.logger.error('[cli]: "--all" applies only to "install". Did you mean "--full"?');
55
67
  process.exit(1);
56
68
  }
69
+ // `mcp` speaks a protocol on stdout and `hook` is invoked by a harness with a
70
+ // fixed payload: neither has anything to configure from the command line, and a
71
+ // flag that quietly did nothing would look like it had.
72
+ if ((cmd === 'mcp' || cmd === 'hook') && flags.length > 0) {
73
+ index_js_2.logger.error(`[cli]: "${cmd}" takes no flags, got: ${flags.join(', ')}.`);
74
+ process.exit(1);
75
+ }
76
+ // Only a command that runs checks has findings to export; `all`, `precommit` and a
77
+ // named check do, every other standalone command does not.
78
+ const runsChecks = !cmd || cmd === 'all' || cmd === 'precommit' || !commands_js_1.STANDALONE_COMMANDS.includes(cmd);
79
+ if (flags.includes('--sarif') && !runsChecks) {
80
+ index_js_2.logger.error('[cli]: "--sarif" applies only to commands that run checks.');
81
+ process.exit(1);
82
+ }
83
+ if (flags.includes('--no-hook') && cmd !== 'agent-setup') {
84
+ index_js_2.logger.error('[cli]: "--no-hook" applies only to "agent-setup".');
85
+ process.exit(1);
86
+ }
87
+ if (flags.includes('--full') && commands_js_1.AGENT_COMMANDS.includes(cmd ?? '')) {
88
+ index_js_2.logger.error(`[cli]: "${cmd}" reviews nothing on its own, so "--full" has no meaning.`);
89
+ process.exit(1);
90
+ }
57
91
  if (flags.includes('--full') && commands_js_1.TOOLING_COMMANDS.includes(cmd ?? '')) {
58
92
  index_js_2.logger.error(`[cli]: "${cmd}" manages tooling and reviews nothing, so "--full" has no meaning.`);
59
93
  process.exit(1);
@@ -75,6 +109,55 @@ function rejectExtraArgs() {
75
109
  index_js_2.logger.error(`[cli]: "${cmd}" takes no other arguments, got: ${args.slice(1).join(', ')}. Run them as a separate command.`);
76
110
  process.exit(1);
77
111
  }
112
+ /**
113
+ * Write the report as SARIF when `--sarif` was passed. Written before the exit code
114
+ * is decided, so a failing run still leaves the file a dashboard needs to show why.
115
+ */
116
+ function writeSarifIfRequested(report) {
117
+ if (!flags.includes('--sarif'))
118
+ return;
119
+ const file = node_path_1.default.resolve(process.cwd(), 'pr-checkmate.sarif');
120
+ node_fs_1.default.writeFileSync(file, `${JSON.stringify((0, sarif_js_1.toSarif)(report, (0, package_version_js_1.packageVersion)()), null, 2)}\n`);
121
+ index_js_2.logger.info(`[sarif]: wrote ${file}`);
122
+ }
123
+ /** Everything the harness wrote to stdin, as text; empty when stdin is closed or a terminal. */
124
+ async function readStdin() {
125
+ if (process.stdin.isTTY)
126
+ return '';
127
+ const chunks = [];
128
+ for await (const chunk of process.stdin)
129
+ chunks.push(Buffer.from(chunk));
130
+ return Buffer.concat(chunks).toString('utf-8');
131
+ }
132
+ /**
133
+ * The commands that serve AI agents. Returns whether `cmd` was one of them (and has
134
+ * therefore already exited); kept out of the main dispatcher so that one stays
135
+ * readable as the list of commands grows.
136
+ *
137
+ * `mcp` must stay ahead of anything that could print: from here until stdin closes,
138
+ * stdout carries protocol messages and nothing else.
139
+ */
140
+ async function runAgentCommand() {
141
+ if (cmd === 'mcp') {
142
+ await (0, serve_js_1.serve)((0, tools_js_1.createServerDefinition)());
143
+ process.exit(0);
144
+ }
145
+ if (cmd === 'hook') {
146
+ // Discarded rather than shown: the harness reads stdout and stderr of a hook
147
+ // as instructions to the model, so only the verdict may reach either.
148
+ (0, execa_js_1.isolateInheritedStdio)('discard');
149
+ index_js_2.logger.setSink({ out: () => undefined, err: () => undefined });
150
+ const verdict = await (0, hook_js_1.evaluateHook)(await readStdin(), process.cwd());
151
+ if (verdict.stderr)
152
+ process.stderr.write(`${verdict.stderr}\n`);
153
+ process.exit(verdict.exitCode);
154
+ }
155
+ if (cmd === 'agent-setup') {
156
+ (0, setup_js_1.reportSetup)((0, setup_js_1.setupAgent)(process.cwd(), { hook: !flags.includes('--no-hook') }));
157
+ process.exit(0);
158
+ }
159
+ return false;
160
+ }
78
161
  void (async () => {
79
162
  try {
80
163
  rejectUnknownFlags();
@@ -84,6 +167,8 @@ void (async () => {
84
167
  await (0, init_js_1.init)();
85
168
  process.exit(0);
86
169
  }
170
+ if (await runAgentCommand())
171
+ return;
87
172
  // Tooling management. These run no checks — they prepare, inspect or clean
88
173
  // up what the checks need, so they never touch the diff or the reporter.
89
174
  if (cmd === 'install') {
@@ -125,12 +210,14 @@ void (async () => {
125
210
  index_js_2.logger.info('');
126
211
  notice.forEach(line => index_js_2.logger.info(line));
127
212
  }
213
+ writeSarifIfRequested(report);
128
214
  process.exit(report.ok ? 0 : 1);
129
215
  }
130
216
  // Local pre-commit: check the staged changes (index vs HEAD), print to
131
217
  // stdout, never modify files. Exits non-zero on failure to block the commit.
132
218
  if (cmd === 'precommit') {
133
219
  const report = await (0, index_js_1.runChecks)({ staged: true, reporter: 'stdout', write: false });
220
+ writeSarifIfRequested(report);
134
221
  process.exit(report.ok ? 0 : 1);
135
222
  }
136
223
  // Every remaining argument is a check name, so `pr-checkmate lint spellcheck`
@@ -143,6 +230,7 @@ void (async () => {
143
230
  }
144
231
  const checkNames = [...new Set(args.map(arg => commands_js_1.COMMAND_TO_CHECK[arg]))];
145
232
  const report = await (0, index_js_1.runChecks)({ only: checkNames, reporter: 'stdout', write: true, full });
233
+ writeSarifIfRequested(report);
146
234
  process.exit(report.ok ? 0 : 1);
147
235
  }
148
236
  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.
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.KNOWN_CONFIG_KEYS = exports.documentation = exports.FULL_CONFIG_URL = exports.DOCS_URL = exports.DEFAULT_ALLOW_PACKAGES = exports.DEFAULT_COMMANDS = exports.SOURCE_EXTENSIONS = exports.DUPLICATE_CODE_FORMATS = exports.CONFIG_FILE_PATTERNS = exports.DEAD_CODE_IGNORE_DEFAULTS = exports.GENERATED_DOC_FILES = exports.DIFF_SECURITY_IGNORE_DEFAULTS = exports.DUPLICATE_IGNORE_DEFAULTS = exports.TEST_PATH_GLOBS = exports.IGNORE_PATTERNS = exports.IGNORED_DIRS = void 0;
3
+ exports.KNOWN_CONFIG_KEYS = exports.documentation = exports.FULL_CONFIG_URL = exports.DOCS_URL = exports.DEFAULT_ALLOW_PACKAGES = exports.DEFAULT_COMMANDS = exports.AGENT_SETUP_COMMAND = exports.SOURCE_EXTENSIONS = exports.DUPLICATE_CODE_FORMATS = exports.CONFIG_FILE_PATTERNS = exports.DEAD_CODE_IGNORE_DEFAULTS = exports.GENERATED_DOC_FILES = exports.DIFF_SECURITY_IGNORE_DEFAULTS = exports.DUPLICATE_IGNORE_DEFAULTS = exports.TEST_PATH_GLOBS = exports.IGNORE_PATTERNS = exports.IGNORED_DIRS = void 0;
4
4
  /**
5
5
  * Build output, dependency, tooling, and report directories that are never
6
6
  * product code. Every check excludes them by directory-name segment match (see
@@ -228,6 +228,7 @@ exports.SOURCE_EXTENSIONS = {
228
228
  json: ['.json'],
229
229
  all: ['.ts', '.tsx', '.js', '.jsx', '.json', '.md', '.mdx'],
230
230
  };
231
+ exports.AGENT_SETUP_COMMAND = 'npx pr-checkmate agent-setup';
231
232
  exports.DEFAULT_COMMANDS = {
232
233
  'npx pr-checkmate init': 'Create pr-checkmate.json and the CI workflow (first-run setup)',
233
234
  'npx pr-checkmate all': 'Run all checks over the changes — the PR diff in CI, your branch changes locally',
@@ -242,6 +243,7 @@ exports.DEFAULT_COMMANDS = {
242
243
  'npx pr-checkmate diff-smell': 'Scan git diff for code smells',
243
244
  'npx pr-checkmate pr-body': 'Validate PR description',
244
245
  'npx pr-checkmate duplicate': 'Detect duplicate code blocks (jscpd)',
246
+ [exports.AGENT_SETUP_COMMAND]: 'Connect your AI agent: MCP server, rules for it and edit hooks (writes .mcp.json)',
245
247
  };
246
248
  /**
247
249
  * Packages allow-listed for the license check by default.
@@ -323,6 +325,8 @@ exports.KNOWN_CONFIG_KEYS = new Set([
323
325
  'diffSecurity',
324
326
  'workflowSecurity',
325
327
  'dockerfileSecurity',
328
+ 'agentInstructions',
329
+ 'mcp',
326
330
  'sensitiveFileGuard',
327
331
  'migrationSafety',
328
332
  // 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,
@@ -23,6 +23,7 @@ const node_fs_1 = __importDefault(require("node:fs"));
23
23
  const node_path_1 = __importDefault(require("node:path"));
24
24
  const execa_js_1 = require("../../utils/execa.js");
25
25
  const index_js_1 = require("../../utils/index.js");
26
+ const finding_store_js_1 = require("../finding-store.js");
26
27
  const targets_js_1 = require("../targets.js");
27
28
  const types_js_1 = require("../types.js");
28
29
  /**
@@ -391,6 +392,8 @@ exports.DEFAULT_DATAFLOW_WINDOW = 10;
391
392
  const CROSS_LINE_SQL_LABEL = 'Interpolated value reaches a query (SQL injection risk, cross-line)';
392
393
  /** `@@ ... @@` — a new hunk, and the boundary taint never crosses. */
393
394
  const DIFF_HUNK_HEADER = /^@@ /;
395
+ /** The first line of the new side of a hunk: `@@ -3,2 +10,4 @@` → 10. */
396
+ const HUNK_NEW_START = /^@@ -\d+(?:,\d+)? \+(\d+)/;
394
397
  /**
395
398
  * Whether this line hands `name` to a query sink.
396
399
  *
@@ -464,6 +467,9 @@ function scanDiffPatterns(stdout, patterns, opts = {}) {
464
467
  const mode = opts.comments ?? 'language';
465
468
  const ignorePaths = opts.ignorePaths ?? [];
466
469
  let syntax = 'both';
470
+ // Where the walk is, for findings that need to say so.
471
+ let file = '';
472
+ let newLine = 0;
467
473
  // Block comments span lines, so the state belongs to the walk, not to one line.
468
474
  let inBlockComment = false;
469
475
  // Whole files can be excluded by glob; the flag persists until the next header.
@@ -474,6 +480,7 @@ function scanDiffPatterns(stdout, patterns, opts = {}) {
474
480
  for (const line of stdout.split('\n')) {
475
481
  const header = DIFF_FILE_HEADER.exec(line);
476
482
  if (header) {
483
+ file = header[1];
477
484
  syntax = mode === 'language' ? commentSyntaxFor(header[1]) : 'both';
478
485
  inBlockComment = false;
479
486
  skippingFile = ignorePaths.length > 0 && (0, index_js_1.matchesAnyGlob)(header[1], ignorePaths);
@@ -482,9 +489,15 @@ function scanDiffPatterns(stdout, patterns, opts = {}) {
482
489
  }
483
490
  // Checked before the `+` filter below, which a hunk header does not satisfy.
484
491
  if (DIFF_HUNK_HEADER.test(line)) {
492
+ newLine = Number(HUNK_NEW_START.exec(line)?.[1] ?? 0);
485
493
  taint.reset();
486
494
  continue;
487
495
  }
496
+ // Counted before any skip: an ignored or excluded line still occupies a line
497
+ // number in the file, and the ones after it must not shift.
498
+ const lineNo = newLine;
499
+ if (line.startsWith('+'))
500
+ newLine++;
488
501
  if (skippingFile)
489
502
  continue;
490
503
  // Only added lines carry block-comment state: a `-` line is code being
@@ -496,18 +509,28 @@ function scanDiffPatterns(stdout, patterns, opts = {}) {
496
509
  const prepared = uncomment(line, { mode, syntax, inBlockComment });
497
510
  inBlockComment = prepared.inBlockComment;
498
511
  const asCode = stripStringLiterals(prepared.text);
499
- for (const { pattern, label, severity, view } of patterns) {
500
- if (pattern.test(view === 'code' ? asCode : prepared.text)) {
501
- const bucket = severity === 'error' ? errors : warnings;
502
- (bucket[label] ?? (bucket[label] = [])).push(line.slice(1).trim().substring(0, SAMPLE_MAX_LENGTH));
503
- }
504
- }
512
+ const where = { file, line: lineNo };
513
+ recordMatches(patterns, { text: prepared.text, asCode }, line, where, { errors, warnings });
505
514
  if (taint.inspect(prepared.text, asCode)) {
506
- (warnings[CROSS_LINE_SQL_LABEL] ?? (warnings[CROSS_LINE_SQL_LABEL] = [])).push(line.slice(1).trim().substring(0, SAMPLE_MAX_LENGTH));
515
+ record(warnings, CROSS_LINE_SQL_LABEL, line, where);
507
516
  }
508
517
  }
509
518
  return { errors, warnings };
510
519
  }
520
+ /** File one added line under `label` and remember where it was, for findings that say so. */
521
+ function record(bucket, label, line, where) {
522
+ const sample = line.slice(1).trim().substring(0, SAMPLE_MAX_LENGTH);
523
+ (bucket[label] ?? (bucket[label] = [])).push(sample);
524
+ (0, finding_store_js_1.noteLocation)(label, sample, where.file, where.line);
525
+ }
526
+ /** File every pattern that matches one prepared line under its own label and severity. */
527
+ function recordMatches(patterns, view, line, where, into) {
528
+ for (const { pattern, label, severity, view: wants } of patterns) {
529
+ if (pattern.test(wants === 'code' ? view.asCode : view.text)) {
530
+ record(severity === 'error' ? into.errors : into.warnings, label, line, where);
531
+ }
532
+ }
533
+ }
511
534
  /**
512
535
  * Reduce one added line to what should be matched against: block comments
513
536
  * blanked (carrying the open state on), then the trailing line comment removed.
@@ -598,6 +621,7 @@ function bucketTotal(bucket) {
598
621
  */
599
622
  function reportCountedFindings(findings, ctx, opts) {
600
623
  const sev = severityEmitter(opts.severity, opts.fallback ?? 'warn');
624
+ (0, finding_store_js_1.fileFindings)(findings, sev.icon === '❌' ? 'error' : 'warn');
601
625
  logFindings(findings, {
602
626
  prefix: opts.prefix,
603
627
  sampleLimit: opts.sampleLimit ?? ctx.config.log?.sampleLimit ?? 3,
@@ -702,6 +726,8 @@ function reportSeverityBuckets(errorsIn, warningsIn, opts) {
702
726
  const ignore = opts.ignore ?? [];
703
727
  const filed = applyOverrides(dropIgnored(errorsIn, ignore), dropIgnored(warningsIn, ignore), opts.severityOverrides ?? {});
704
728
  const { errors, warnings } = filed;
729
+ (0, finding_store_js_1.fileFindings)(errors, 'error');
730
+ (0, finding_store_js_1.fileFindings)(warnings, 'warn');
705
731
  const totalErrors = bucketTotal(errors);
706
732
  const totalWarnings = bucketTotal(warnings);
707
733
  if (totalErrors === 0 && totalWarnings === 0)
@@ -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;
@@ -3,7 +3,7 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
3
3
  return (mod && mod.__esModule) ? mod : { "default": mod };
4
4
  };
5
5
  Object.defineProperty(exports, "__esModule", { value: true });
6
- exports.largeFilesCheck = void 0;
6
+ exports.largeFilesCheck = exports.DEFAULT_MAX_KB = void 0;
7
7
  const node_fs_1 = __importDefault(require("node:fs"));
8
8
  const node_path_1 = __importDefault(require("node:path"));
9
9
  const execa_js_1 = require("../../../utils/execa.js");
@@ -11,7 +11,7 @@ const index_js_1 = require("../../../utils/index.js");
11
11
  const targets_js_1 = require("../../targets.js");
12
12
  const types_js_1 = require("../../types.js");
13
13
  const findings_js_1 = require("../findings.js");
14
- const DEFAULT_MAX_KB = 500;
14
+ exports.DEFAULT_MAX_KB = 500;
15
15
  /**
16
16
  * Lockfiles are legitimately large and always generated, never accidental — so
17
17
  * they're exempt from the size/binary guard by default (a 600 KB
@@ -70,7 +70,7 @@ exports.largeFilesCheck = {
70
70
  return (0, types_js_1.skip)('git unavailable');
71
71
  if (files.length === 0)
72
72
  return (0, types_js_1.pass)();
73
- const maxKb = ctx.config.largeFiles?.maxSizeKb ?? DEFAULT_MAX_KB;
73
+ const maxKb = ctx.config.largeFiles?.maxSizeKb ?? exports.DEFAULT_MAX_KB;
74
74
  const maxBytes = maxKb * 1024;
75
75
  const allow = [...LOCKFILE_ALLOW, ...(ctx.config.largeFiles?.allow ?? [])];
76
76
  if (!ctx.baseSha && ctx.config.run?.fullScanBehaviour === 'skip')
@@ -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,11 +1,11 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.prSizeCheck = void 0;
3
+ exports.prSizeCheck = exports.DEFAULT_MAX_LINES = exports.DEFAULT_MAX_FILES = void 0;
4
4
  const execa_js_1 = require("../../../utils/execa.js");
5
5
  const index_js_1 = require("../../../utils/index.js");
6
6
  const types_js_1 = require("../../types.js");
7
- const DEFAULT_MAX_FILES = 50;
8
- const DEFAULT_MAX_LINES = 1000;
7
+ exports.DEFAULT_MAX_FILES = 50;
8
+ exports.DEFAULT_MAX_LINES = 1000;
9
9
  exports.prSizeCheck = {
10
10
  name: 'PR Size',
11
11
  phase: 'informational',
@@ -14,8 +14,8 @@ exports.prSizeCheck = {
14
14
  return ctx.config.prSize?.enabled !== false;
15
15
  },
16
16
  async run(ctx) {
17
- const maxFiles = ctx.config.prSize?.maxFiles ?? DEFAULT_MAX_FILES;
18
- const maxLines = ctx.config.prSize?.maxLines ?? DEFAULT_MAX_LINES;
17
+ const maxFiles = ctx.config.prSize?.maxFiles ?? exports.DEFAULT_MAX_FILES;
18
+ const maxLines = ctx.config.prSize?.maxLines ?? exports.DEFAULT_MAX_LINES;
19
19
  try {
20
20
  const { stdout } = await (0, execa_js_1.execa)('git', ['diff', '--shortstat', ctx.baseSha, ctx.headSha ?? 'HEAD'], {
21
21
  cwd: ctx.cwd,
@@ -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;
@@ -0,0 +1,149 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.agentInstructionsCheck = exports.AGENT_PATTERNS = void 0;
4
+ // cspell:ignore windsurfrules
5
+ const index_js_1 = require("../../../utils/index.js");
6
+ const targets_js_1 = require("../../targets.js");
7
+ const types_js_1 = require("../../types.js");
8
+ const findings_js_1 = require("../findings.js");
9
+ /**
10
+ * Files that tell an AI agent what to do, or what it may do.
11
+ *
12
+ * They are code in every sense that matters: an agent reads them and acts, with
13
+ * the developer's shell and the developer's credentials. A pull request that edits
14
+ * one changes what every contributor's agent will do on its next run, and the diff
15
+ * is prose — which review tends to skim. That makes this the cheapest place in a
16
+ * repository to plant an instruction, and the least reviewed.
17
+ */
18
+ const INSTRUCTION_GLOBS = [
19
+ 'AGENTS.md',
20
+ '**/AGENTS.md',
21
+ 'CLAUDE.md',
22
+ '**/CLAUDE.md',
23
+ 'GEMINI.md',
24
+ '.cursorrules',
25
+ '.windsurfrules',
26
+ '.cursor/rules/**',
27
+ '.github/copilot-instructions.md',
28
+ '.claude/commands/**',
29
+ '.claude/agents/**',
30
+ '.claude/skills/**',
31
+ '.claude/settings.json',
32
+ '.mcp.json',
33
+ ];
34
+ /** Dot-directories the file walk drops by default and this check lives in. */
35
+ const KEEP_DIRS = ['.claude', '.cursor', '.github'];
36
+ /**
37
+ * Characters a person cannot see and a model reads anyway: zero-width characters,
38
+ * bidirectional overrides and the Unicode "tag" block. Each has been used to hide
39
+ * an instruction inside text that looks harmless on screen. A byte-order mark is
40
+ * left out on purpose — editors put one at the top of ordinary files.
41
+ */
42
+ const INVISIBLE = '[\\u200B-\\u200F\\u202A-\\u202E\\u2060-\\u2064\\u2066-\\u2069]|[\\u{E0000}-\\u{E007F}]';
43
+ exports.AGENT_PATTERNS = [
44
+ {
45
+ pattern: new RegExp(`^\\+(?!\\+).*(?:${INVISIBLE})`, 'u'),
46
+ label: 'invisible Unicode characters (can hide instructions from a human reviewer)',
47
+ severity: 'error',
48
+ },
49
+ {
50
+ pattern:
51
+ // "Do not add X without telling the user" asks the agent to check in, so a
52
+ // `without` that follows a negation in the same sentence is not a match.
53
+ /^\+(?!\+)(?![^\n]*\b(?:do not|don't|never)\b[^.\n]*\bwithout\b).*\b(?:do not|don't|never|without)\b[^.\n]{0,30}\b(?:tell|telling|inform|informing|mention|show|reveal|notify)\b[^.\n]{0,20}\b(?:the )?(?:user|developer|human)\b/i,
54
+ label: 'tells the agent to hide something from the user',
55
+ severity: 'error',
56
+ },
57
+ {
58
+ pattern: /^\+(?!\+).*\b(?:send|post|upload|curl|wget|fetch|exfiltrate|email)\b[^\n]{0,80}(?:\.env\b|credentials?|secrets?|api[_ -]?keys?|\btokens?\b|\bssh\b|id_rsa)[^\n]{0,80}https?:\/\//i,
59
+ label: 'sends credentials or secrets to a URL',
60
+ severity: 'error',
61
+ },
62
+ {
63
+ pattern: /^\+(?!\+).*\b(?:ignore|disregard|forget|override)\b[^.\n]{0,40}\b(?:previous|prior|above|earlier|all|any)\b[^.\n]{0,30}\b(?:instructions?|rules|prompts?|guidelines)\b/i,
64
+ label: 'prompt-injection phrasing ("ignore previous instructions")',
65
+ severity: 'warn',
66
+ },
67
+ {
68
+ pattern: /^\+(?!\+).*\b(?:curl|wget)\b[^|\n]*\|\s*(?:sudo\s+)?(?:sh|bash|zsh)\b/i,
69
+ label: 'pipes a download straight into a shell (an agent will run what it is told to run)',
70
+ severity: 'warn',
71
+ },
72
+ {
73
+ pattern: /^\+(?!\+).*(?:--no-verify|--dangerously-skip-permissions|--no-gpg-sign)\b/,
74
+ label: 'instructs the agent to skip a safety check',
75
+ severity: 'warn',
76
+ },
77
+ {
78
+ pattern: /^\+(?!\+)\s*"defaultMode"\s*:\s*"bypassPermissions"/,
79
+ label: 'bypassPermissions as the project default (every contributor’s agent runs without asking)',
80
+ severity: 'error',
81
+ },
82
+ {
83
+ pattern: /^\+(?!\+)\s*"enableAllProjectMcpServers"\s*:\s*true/,
84
+ label: 'auto-approves every MCP server this repository declares',
85
+ severity: 'warn',
86
+ },
87
+ {
88
+ pattern: /^\+(?!\+)\s*"(?:Bash|Write|Edit)(?:\((?:\*|:\*)\))?"\s*,?\s*$/,
89
+ label: 'permission granted for every shell command or file write',
90
+ severity: 'warn',
91
+ },
92
+ {
93
+ pattern: /^\+(?!\+).*"url"\s*:\s*"http:\/\/(?!localhost|127\.0\.0\.1|\[::1\])/,
94
+ label: 'MCP server reached over plain HTTP',
95
+ severity: 'warn',
96
+ },
97
+ {
98
+ // `"args": ["-y", "pkg"]` with no @version: whatever is published next runs on
99
+ // the machine of everyone who opens the repository.
100
+ pattern: /^\+(?!\+).*"args"\s*:\s*\[\s*"-y"\s*,\s*"(?:@[^/"@]+\/)?[^"@]+"/,
101
+ label: 'MCP server fetched with npx and no pinned version (the next publish runs on every contributor’s machine)',
102
+ severity: 'warn',
103
+ },
104
+ ];
105
+ exports.agentInstructionsCheck = {
106
+ name: 'Agent Instructions',
107
+ phase: 'informational',
108
+ // No `requiresDiff`: a hidden instruction is as live in a file that arrived last
109
+ // year as in one added today, so a whole-repository run reads them too.
110
+ applies(ctx) {
111
+ return ctx.config.agentInstructions?.enabled !== false;
112
+ },
113
+ async run(ctx) {
114
+ try {
115
+ const cfg = ctx.config.agentInstructions ?? {};
116
+ const found = (0, findings_js_1.emptyBuckets)();
117
+ const scanInto = (stdout) => {
118
+ // `comments: 'off'`: these are Markdown and JSON, where a leading `#` is a
119
+ // heading and `//` is part of a URL — stripping them as comments would
120
+ // blank exactly the lines worth reading.
121
+ (0, findings_js_1.mergeSeverityBuckets)(found, (0, findings_js_1.scanDiffPatterns)(stdout, exports.AGENT_PATTERNS, {
122
+ comments: 'off',
123
+ ignorePaths: cfg.ignorePaths,
124
+ }));
125
+ };
126
+ if (ctx.baseSha) {
127
+ scanInto(await (0, findings_js_1.diffAddedLines)(ctx, INSTRUCTION_GLOBS));
128
+ }
129
+ else if (ctx.config.run?.fullScanBehaviour !== 'skip') {
130
+ const files = await (0, targets_js_1.listTrackedFiles)(ctx, INSTRUCTION_GLOBS, ['.'], {
131
+ keepDirs: KEEP_DIRS,
132
+ });
133
+ if (files === null)
134
+ return (0, types_js_1.skip)('git unavailable');
135
+ await (0, findings_js_1.scanTrackedFiles)(ctx, files, scanInto);
136
+ }
137
+ return (0, findings_js_1.reportSeverityBuckets)(found.errors, found.warnings, {
138
+ prefix: 'Agent Instructions',
139
+ errorSummary: n => `${n} issue(s)`,
140
+ warningSummary: n => `${n} warning(s)`,
141
+ ...(0, findings_js_1.clientFindingOptions)(ctx, cfg),
142
+ });
143
+ }
144
+ catch (err) {
145
+ index_js_1.logger.warn(`[Agent Instructions]: ⚠️ Could not analyze agent files\n${err}`);
146
+ return (0, types_js_1.skip)('agent files unavailable');
147
+ }
148
+ },
149
+ };
@@ -1,2 +1,9 @@
1
1
  import { Check } from '../../types.js';
2
+ import { DiffPattern } from '../findings.js';
3
+ /**
4
+ * npm supply-chain entry points, matched in `package.json`. Both are how a
5
+ * compromised package reaches a developer machine or CI runner, so they are
6
+ * worth a human look whenever one is added — neither is wrong by itself.
7
+ */
8
+ export declare const PACKAGE_JSON_PATTERNS: DiffPattern[];
2
9
  export declare const diffSecurityCheck: Check;
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.diffSecurityCheck = void 0;
3
+ exports.diffSecurityCheck = exports.PACKAGE_JSON_PATTERNS = void 0;
4
4
  const index_js_1 = require("../../../config/index.js");
5
5
  const index_js_2 = require("../../../utils/index.js");
6
6
  const types_js_1 = require("../../types.js");
@@ -235,6 +235,25 @@ const KOTLIN_SECURITY_PATTERNS = [
235
235
  },
236
236
  ];
237
237
  const JS_GLOBS = ['*.ts', '*.tsx', '*.js', '*.jsx', '*.mjs', '*.cjs'];
238
+ const PACKAGE_JSON_GLOBS = ['package.json', '*/package.json'];
239
+ /**
240
+ * npm supply-chain entry points, matched in `package.json`. Both are how a
241
+ * compromised package reaches a developer machine or CI runner, so they are
242
+ * worth a human look whenever one is added — neither is wrong by itself.
243
+ */
244
+ exports.PACKAGE_JSON_PATTERNS = [
245
+ {
246
+ pattern: /^\+(?!\+)\s*"(?:preinstall|install|postinstall)"\s*:/,
247
+ label: 'npm install lifecycle script (runs on every consumer install)',
248
+ severity: 'warn',
249
+ },
250
+ {
251
+ // `repository.url` is the one key that legitimately holds a `git+https:` value.
252
+ pattern: /^\+(?!\+)\s*"(?!url")[^"]+"\s*:\s*"(?:git\+[a-z]+:|git:\/\/|git@|github:|https?:\/\/[^"]+\.(?:tgz|tar\.gz)")/,
253
+ label: 'dependency from a git or tarball URL (bypasses registry integrity and audit)',
254
+ severity: 'warn',
255
+ },
256
+ ];
238
257
  /**
239
258
  * Compile the client's `extraPatterns` into the same shape as the built-ins, so
240
259
  * a project rule gets identical treatment: comment stripping, the code/raw view,
@@ -323,6 +342,7 @@ exports.diffSecurityCheck = {
323
342
  // Client `extraPatterns` run against every scanned language, since a
324
343
  // project rule is not tied to the built-in language split.
325
344
  const sets = [[JS_GLOBS, [...SECURITY_PATTERNS, ...extra]]];
345
+ sets.push([PACKAGE_JSON_GLOBS, exports.PACKAGE_JSON_PATTERNS]);
326
346
  if (ctx.languages.includes('python')) {
327
347
  sets.push([['*.py'], [...PYTHON_SECURITY_PATTERNS, ...extra]]);
328
348
  }
@@ -30,19 +30,6 @@ import { Check } from '../../types.js';
30
30
  * the caller keeps its old wording rather than claiming a number it does not have.
31
31
  */
32
32
  export declare function countFindings(reportPath: string): number | null;
33
- /**
34
- * How the outcome names what was found.
35
- *
36
- * Its own function so both halves are reachable without running the scanner. The
37
- * corpus for this check deliberately does not: the wrapper downloads a gitleaks
38
- * binary on first use, and a unit suite that reaches the network is the thing the
39
- * `installer` seam in `ensure.ts` exists to avoid. What broke here was the wording
40
- * — a row that read the same for one secret and for thirty-nine — and the wording
41
- * is testable on its own.
42
- *
43
- * `null` keeps the old sentence rather than inventing a number: a report we could
44
- * not read is not a reason to claim a count.
45
- */
46
33
  export declare function secretsSummary(found: number | null): string;
47
34
  /**
48
35
  * Whether the wrapper died instead of reporting, judged from its stderr.
@@ -13,6 +13,7 @@ const node_path_1 = __importDefault(require("node:path"));
13
13
  const index_js_1 = require("../../../config/index.js");
14
14
  const execa_js_1 = require("../../../utils/execa.js");
15
15
  const index_js_2 = require("../../../utils/index.js");
16
+ const finding_store_js_1 = require("../../finding-store.js");
16
17
  const types_js_1 = require("../../types.js");
17
18
  /**
18
19
  * A HOME the scanner can actually write to.
@@ -66,6 +67,31 @@ function countFindings(reportPath) {
66
67
  * `null` keeps the old sentence rather than inventing a number: a report we could
67
68
  * not read is not a reason to claim a count.
68
69
  */
70
+ /**
71
+ * Tell the report where each leak is. The secret itself is never copied: the
72
+ * finding carries a file, a line and the rule that matched, which is all anyone
73
+ * needs to go and remove it — and all that is safe to hand to an agent's context.
74
+ */
75
+ function recordLeaks(reportPath, cwd) {
76
+ try {
77
+ const report = JSON.parse(node_fs_1.default.readFileSync(reportPath, 'utf-8'));
78
+ if (!Array.isArray(report))
79
+ return;
80
+ for (const leak of report) {
81
+ if (typeof leak?.File !== 'string')
82
+ continue;
83
+ (0, finding_store_js_1.addFinding)({
84
+ file: node_path_1.default.isAbsolute(leak.File) ? node_path_1.default.relative(cwd, leak.File) : leak.File,
85
+ line: typeof leak.StartLine === 'number' ? leak.StartLine : undefined,
86
+ rule: typeof leak.RuleID === 'string' ? leak.RuleID : 'secret',
87
+ severity: 'error',
88
+ });
89
+ }
90
+ }
91
+ catch {
92
+ // An unreadable report already shows up as an uncounted summary; no locations to add.
93
+ }
94
+ }
69
95
  function secretsSummary(found) {
70
96
  return found === null ? 'potential secrets detected' : `${found} potential secret(s)`;
71
97
  }
@@ -186,6 +212,7 @@ exports.securityCheck = {
186
212
  if (stderr.trim())
187
213
  index_js_2.logger.warn(stderr.trimEnd());
188
214
  const found = countFindings(reportPath);
215
+ recordLeaks(reportPath, ctx.cwd);
189
216
  node_fs_1.default.rmSync(reportDir, { recursive: true, force: true });
190
217
  if (result.exitCode === 0)
191
218
  return (0, types_js_1.pass)();