@boyingliu01/xp-gate 0.38.9 → 0.38.11

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 (50) hide show
  1. package/adapters/shell.sh +87 -2
  2. package/hooks/gate-entries/gate-0-entry.sh +48 -3
  3. package/hooks/gate-entries/gate-12-entry.sh +20 -1
  4. package/hooks/gate-entries/gate-5-entry.sh +56 -2
  5. package/hooks/pre-commit +40 -0
  6. package/lib/__tests__/baseline-completeness.test.js +264 -0
  7. package/lib/baseline.js +265 -86
  8. package/lib/mattpocock-license-verdict.json +1 -1
  9. package/mock-policy/AGENTS.md +85 -83
  10. package/mutation/AGENTS.md +87 -61
  11. package/package.json +1 -1
  12. package/plugins/claude-code/.claude-plugin/plugin.json +1 -1
  13. package/plugins/claude-code/skills/delphi-review/AGENTS.md +1 -1
  14. package/plugins/claude-code/skills/ralph-loop/SKILL.md +1 -1
  15. package/plugins/claude-code/skills/ralph-loop/references/components.md +1 -1
  16. package/plugins/claude-code/skills/sprint-flow/AGENTS.md +3 -3
  17. package/plugins/claude-code/skills/sprint-flow/__tests__/sprint-flow.test.cjs +25 -7
  18. package/plugins/claude-code/skills/sprint-flow/references/phase-overview.md +3 -3
  19. package/plugins/claude-code/skills/test-specification-alignment/AGENTS.md +1 -1
  20. package/plugins/dsh/package.json +1 -1
  21. package/plugins/dsh/skills/delphi-review/AGENTS.md +1 -1
  22. package/plugins/dsh/skills/ralph-loop/SKILL.md +1 -1
  23. package/plugins/dsh/skills/ralph-loop/references/components.md +1 -1
  24. package/plugins/dsh/skills/sprint-flow/AGENTS.md +3 -3
  25. package/plugins/dsh/skills/sprint-flow/__tests__/sprint-flow.test.cjs +25 -7
  26. package/plugins/dsh/skills/sprint-flow/references/phase-overview.md +3 -3
  27. package/plugins/dsh/skills/test-specification-alignment/AGENTS.md +1 -1
  28. package/plugins/opencode/package.json +1 -1
  29. package/plugins/opencode/skills/delphi-review/AGENTS.md +1 -1
  30. package/plugins/opencode/skills/ralph-loop/SKILL.md +1 -1
  31. package/plugins/opencode/skills/ralph-loop/references/components.md +1 -1
  32. package/plugins/opencode/skills/sprint-flow/AGENTS.md +3 -3
  33. package/plugins/opencode/skills/sprint-flow/__tests__/sprint-flow.test.cjs +25 -7
  34. package/plugins/opencode/skills/sprint-flow/references/phase-overview.md +3 -3
  35. package/plugins/opencode/skills/test-specification-alignment/AGENTS.md +1 -1
  36. package/plugins/qoder/plugin.json +1 -1
  37. package/plugins/qoder/skills/delphi-review/AGENTS.md +1 -1
  38. package/plugins/qoder/skills/ralph-loop/SKILL.md +1 -1
  39. package/plugins/qoder/skills/ralph-loop/references/components.md +1 -1
  40. package/plugins/qoder/skills/sprint-flow/AGENTS.md +3 -3
  41. package/plugins/qoder/skills/sprint-flow/__tests__/sprint-flow.test.cjs +25 -7
  42. package/plugins/qoder/skills/sprint-flow/references/phase-overview.md +3 -3
  43. package/plugins/qoder/skills/test-specification-alignment/AGENTS.md +1 -1
  44. package/principles/AGENTS.md +103 -97
  45. package/skills/delphi-review/AGENTS.md +1 -1
  46. package/skills/ralph-loop/SKILL.md +1 -1
  47. package/skills/ralph-loop/references/components.md +1 -1
  48. package/skills/sprint-flow/AGENTS.md +3 -3
  49. package/skills/sprint-flow/references/phase-overview.md +3 -3
  50. package/skills/test-specification-alignment/AGENTS.md +1 -1
package/lib/baseline.js CHANGED
@@ -38,15 +38,164 @@ function parseArgs(subargs) {
38
38
  /**
39
39
  * Run a lint tool and return its JSON output.
40
40
  */
41
- function runToolJson(toolCmd, pipeToJsonFlag) {
42
- try {
43
- const cmd = `${toolCmd} ${pipeToJsonFlag}`;
44
- return execSync(cmd, { encoding: 'utf8', maxBuffer: 10 * 1024 * 1024 }).trim();
45
- } catch (e) {
46
- // Lint tools exit non-zero when they find issues - that's expected
47
- if (e.stdout) return e.stdout.trim();
48
- return '';
41
+ // How many paths to pass to a linter in one call.
42
+ //
43
+ // A single argv built from every source file is not a style problem, it is a
44
+ // correctness one: this repo has 652 TS/JS files and the joined list measured
45
+ // 31,917 characters against a Windows limit around 8,191. The call always failed,
46
+ // the failure was swallowed, and the baseline recorded zero eslint entries -- so
47
+ // Gate 1 compared every TS/JS file against a baseline of nothing.
48
+ //
49
+ // 100 paths keeps the argv in the low thousands of characters even for deep
50
+ // paths, well clear of the limit on every platform.
51
+ const LINT_BATCH_SIZE = 100;
52
+
53
+ /**
54
+ * Run a lint tool over a list of paths, in batches, and return its findings.
55
+ *
56
+ * Returns an object rather than a bare string so the caller can tell apart the
57
+ * two states that used to be identical: "the tool ran and found nothing" versus
58
+ * "the tool could not be evaluated". Collapsing them is how a baselining command
59
+ * reports success while having measured nothing.
60
+ *
61
+ * @param {string[]} files project-relative paths
62
+ * @param {(batch: string[]) => string} buildCmd builds the command line for a batch
63
+ * @param {string} jsonFlag flag that makes the tool emit JSON on stdout
64
+ * @returns {{results: any[], errors: string[]}} parsed per-batch results, or a
65
+ * list of failure messages. An empty `results` with a non-empty `errors` means
66
+ * "not evaluated", never "clean".
67
+ */
68
+ function runLintInBatches(files, buildCmd, jsonFlag) {
69
+ const results = [];
70
+ const errors = [];
71
+
72
+ for (let i = 0; i < files.length; i += LINT_BATCH_SIZE) {
73
+ const batch = files.slice(i, i + LINT_BATCH_SIZE);
74
+ let stdout;
75
+ try {
76
+ stdout = execSync(`${buildCmd(batch)} ${jsonFlag}`, {
77
+ encoding: 'utf8',
78
+ maxBuffer: 10 * 1024 * 1024,
79
+ });
80
+ } catch (e) {
81
+ // Non-zero exit is the tool's normal answer when it FOUND something, and
82
+ // its stdout still carries the JSON. Only an empty stdout is a failure.
83
+ stdout = e.stdout;
84
+ if (!stdout || !String(stdout).trim()) {
85
+ errors.push(formatToolFailure(e));
86
+ continue;
87
+ }
88
+ }
89
+ const trimmed = String(stdout).trim();
90
+ if (!trimmed) continue;
91
+ try {
92
+ const parsed = JSON.parse(trimmed);
93
+ if (Array.isArray(parsed)) results.push(...parsed);
94
+ } catch {
95
+ errors.push(`linter returned unparseable output for ${batch.length} file(s)`);
96
+ }
97
+ }
98
+
99
+ return { results, errors };
100
+ }
101
+
102
+ /**
103
+ * Resolve a tool installed in `node_modules/.bin` to something execSync can run.
104
+ *
105
+ * `fs.existsSync('node_modules/.bin/eslint')` is not enough on Windows, and the
106
+ * path it returns cannot be executed there at all. Measured on this machine:
107
+ *
108
+ * node_modules/.bin/eslint -> cmd.exe reports "'node_modules' is not
109
+ * recognized" (a relative path is not an
110
+ * executable name to cmd)
111
+ * node node_modules/.bin/eslint -> SyntaxError, because the extensionless
112
+ * entry is a POSIX sh wrapper
113
+ * node_modules/.bin/eslint.cmd -> same "not recognized" failure
114
+ * absolute path to eslint.cmd -> works (v10.3.0)
115
+ *
116
+ * So the resolution has to produce an ABSOLUTE path and pick the platform's
117
+ * launcher: `.cmd` on Windows, the bare script elsewhere.
118
+ *
119
+ * @param {string} name tool name, e.g. 'eslint'
120
+ * @param {string} [cwd] directory to resolve against
121
+ * @returns {string|null} absolute path to an executable, or null
122
+ */
123
+ function resolveLocalBin(name, cwd = process.cwd()) {
124
+ const binDir = path.join(cwd, 'node_modules', '.bin');
125
+ const candidates = process.platform === 'win32'
126
+ ? [`${name}.cmd`, name]
127
+ : [name];
128
+
129
+ for (const candidate of candidates) {
130
+ const full = path.join(binDir, candidate);
131
+ try {
132
+ if (fs.existsSync(full)) return full;
133
+ } catch {
134
+ // Unreadable candidate -- try the next one.
135
+ }
136
+ }
137
+ return null;
138
+ }
139
+
140
+ /**
141
+ * Format a resolved binary for use inside a shell command line.
142
+ *
143
+ * The path is quoted because node_modules can live under a directory with spaces
144
+ * ("C:\Program Files\..."), which would otherwise split into several args.
145
+ */
146
+ function quoteBin(bin) {
147
+ return `"${bin}"`;
148
+ }
149
+
150
+ /** One-line reason a tool run failed, from the error object execSync threw. */
151
+ function formatToolFailure(err) {
152
+ const stderr = err && err.stderr ? String(err.stderr).trim() : '';
153
+ if (stderr) {
154
+ // The Windows "command line is too long" case prints exactly this; naming it
155
+ // is what turns an invisible defect into a one-line diagnosis.
156
+ return stderr.split('\n')[0].trim();
49
157
  }
158
+ const msg = err && err.message ? String(err.message) : 'unknown error';
159
+ const status = err && typeof err.status === 'number' ? ` (exit ${err.status})` : '';
160
+ return `${msg.split('\n')[0].trim()}${status}`;
161
+ }
162
+
163
+ /**
164
+ * Report a linter that could not be evaluated.
165
+ *
166
+ * Silence is what let "TypeScript was never baselined" survive in this repo: the
167
+ * command printed a cheerful "✅ Baseline created" while 652 files had contributed
168
+ * nothing. A warning is the minimum contract -- the caller can still finish, but
169
+ * the user is told which language went unmeasured and why.
170
+ *
171
+ * @param {string} tool
172
+ * @param {string[]} errors
173
+ */
174
+ function recordFailures(tool, errors) {
175
+ if (!errors || errors.length === 0) return;
176
+ const unique = [...new Set(errors)];
177
+ const shown = unique.slice(0, 3).join('; ');
178
+ const more = unique.length > 3 ? ` (+${unique.length - 3} more)` : '';
179
+ console.warn(`⚠️ ${tool}: could not evaluate ${errors.length} batch(es) — ${shown}${more}`);
180
+ console.warn(` Files covered by a failed batch are absent from the baseline, not clean.`);
181
+ }
182
+
183
+ /**
184
+ * Match a linter's reported path back to one of the files we asked about.
185
+ *
186
+ * Returns null rather than undefined when nothing matches. The previous version
187
+ * used the result of `Array.prototype.find` as an object key, which stringifies
188
+ * an unmatched lookup to the literal key "undefined" -- one bogus baseline entry
189
+ * that made "71 files tracked" print for 70 real files.
190
+ *
191
+ * @param {string} reportedPath absolute or relative path from the tool
192
+ * @param {string[]} candidates the files handed to the tool
193
+ * @returns {string|null}
194
+ */
195
+ function matchResultToFile(reportedPath, candidates) {
196
+ if (!reportedPath) return null;
197
+ const normalized = String(reportedPath).replace(/\\/g, '/');
198
+ return candidates.find(f => normalized.endsWith(f)) || null;
50
199
  }
51
200
 
52
201
  /**
@@ -129,64 +278,84 @@ async function createBaseline() {
129
278
  // TypeScript/JavaScript — ESLint
130
279
  const tsFiles = findFilesByExt(['.ts', '.tsx', '.js', '.jsx']);
131
280
  if (tsFiles.length > 0) {
132
- try {
133
- const eslintConfigExists = fs.existsSync('.eslintrc.json') ||
134
- fs.existsSync('.eslintrc.js') ||
135
- fs.existsSync('.eslintrc.cjs') ||
136
- fs.existsSync('eslint.config.js');
137
- const eslintBin = fs.existsSync('node_modules/.bin/eslint') ? 'node_modules/.bin/eslint' : null;
138
-
139
- if (eslintConfigExists && (eslintBin || execSync('npx eslint --version', { encoding: 'utf8' }))) {
140
- const eslintCmd = eslintBin || 'npx eslint';
141
- const output = runToolJson(`${eslintCmd} ${tsFiles.join(' ')}`, '-f json --no-warn-ignored');
142
- if (output && output !== '[]') {
143
- const parsed = JSON.parse(output);
144
- for (const fileResult of parsed) {
145
- const relativePath = fileResult.filePath;
146
- const fileName = tsFiles.find(f => relativePath.endsWith(f));
147
- if (!fileName) continue;
148
-
149
- baseline[fileName] = {
150
- eslint: {
151
- warnings: fileResult.warningCount || 0,
152
- errors: fileResult.errorCount || 0,
153
- },
154
- totalWarnings: fileResult.warningCount || 0,
155
- lastAnalyzed: new Date().toISOString(),
156
- };
157
- }
158
- }
281
+ const eslintConfigExists = fs.existsSync('.eslintrc.json') ||
282
+ fs.existsSync('.eslintrc.js') ||
283
+ fs.existsSync('.eslintrc.cjs') ||
284
+ fs.existsSync('eslint.config.js');
285
+ const eslintBin = resolveLocalBin('eslint');
286
+
287
+ let eslintAvailable = Boolean(eslintBin);
288
+ if (!eslintAvailable) {
289
+ try {
290
+ execSync('npx eslint --version', { encoding: 'utf8', stdio: 'pipe' });
291
+ eslintAvailable = true;
292
+ } catch {
293
+ eslintAvailable = false;
159
294
  }
160
- } catch {
161
- // ESLint unavailable — skip
295
+ }
296
+
297
+ if (eslintConfigExists && eslintAvailable) {
298
+ const eslintCmd = eslintBin ? quoteBin(eslintBin) : 'npx eslint';
299
+ const { results, errors } = runLintInBatches(
300
+ tsFiles,
301
+ batch => `${eslintCmd} ${batch.map(f => `"${f}"`).join(' ')}`,
302
+ '-f json --no-warn-ignored'
303
+ );
304
+ recordFailures('eslint', errors);
305
+ for (const fileResult of results) {
306
+ const fileName = matchResultToFile(fileResult.filePath, tsFiles);
307
+ if (!fileName) continue;
308
+
309
+ baseline[fileName] = {
310
+ eslint: {
311
+ warnings: fileResult.warningCount || 0,
312
+ errors: fileResult.errorCount || 0,
313
+ },
314
+ totalWarnings: fileResult.warningCount || 0,
315
+ lastAnalyzed: new Date().toISOString(),
316
+ };
317
+ }
318
+ } else if (tsFiles.length > 0 && !eslintConfigExists) {
319
+ // Not a failure: a project without an eslint config has nothing to
320
+ // baseline. Staying quiet here is correct; the silent-catch defect was
321
+ // about masking errors, not about projects that legitimately have no tool.
162
322
  }
163
323
  }
164
324
 
165
325
  // Python — ruff
166
326
  const pyFiles = findFilesByExt(['.py']);
167
327
  if (pyFiles.length > 0) {
328
+ let ruffAvailable = false;
168
329
  try {
169
- execSync('ruff --version', { encoding: 'utf8' });
170
- const output = runToolJson(`ruff check ${pyFiles.join(' ')}`, '--output-format json');
171
- if (output && output !== '[]') {
172
- const parsed = JSON.parse(output);
173
- for (const fileResult of parsed) {
174
- if (!baseline[fileResult.file]) {
175
- const messages = fileResult.messages || [];
176
- baseline[fileResult.file] = {
177
- ruff: { warnings: messages.length, errors: 0 },
178
- totalWarnings: messages.length,
179
- lastAnalyzed: new Date().toISOString(),
180
- };
181
- } else {
182
- const messages = fileResult.messages || [];
183
- baseline[fileResult.file].ruff = { warnings: messages.length, errors: 0 };
184
- baseline[fileResult.file].totalWarnings += messages.length;
185
- }
330
+ execSync('ruff --version', { encoding: 'utf8', stdio: 'pipe' });
331
+ ruffAvailable = true;
332
+ } catch {
333
+ ruffAvailable = false;
334
+ }
335
+
336
+ if (ruffAvailable) {
337
+ const { results, errors } = runLintInBatches(
338
+ pyFiles,
339
+ batch => `ruff check ${batch.map(f => `"${f}"`).join(' ')}`,
340
+ '--output-format json'
341
+ );
342
+ recordFailures('ruff', errors);
343
+ for (const fileResult of results) {
344
+ // A result that names no file cannot be recorded against one. Skipping it
345
+ // is the fix for the literal "undefined" key this used to write.
346
+ if (!fileResult.file) continue;
347
+ const messages = fileResult.messages || [];
348
+ if (!baseline[fileResult.file]) {
349
+ baseline[fileResult.file] = {
350
+ ruff: { warnings: messages.length, errors: 0 },
351
+ totalWarnings: messages.length,
352
+ lastAnalyzed: new Date().toISOString(),
353
+ };
354
+ } else {
355
+ baseline[fileResult.file].ruff = { warnings: messages.length, errors: 0 };
356
+ baseline[fileResult.file].totalWarnings += messages.length;
186
357
  }
187
358
  }
188
- } catch {
189
- // Ruff unavailable — skip
190
359
  }
191
360
  }
192
361
 
@@ -232,39 +401,49 @@ async function createBaseline() {
232
401
  // Shell — shellcheck
233
402
  const shFiles = findShellScripts();
234
403
  if (shFiles.length > 0) {
404
+ let shAvailable = false;
235
405
  try {
236
- execSync('shellcheck --version', { encoding: 'utf8' });
237
- const output = runToolJson(`shellcheck -f json ${shFiles.join(' ')}`, '');
238
- if (output && output !== '[]') {
239
- const parsed = JSON.parse(output);
240
- const warningsByFile = {};
241
- for (const item of parsed) {
242
- const matchedFile = shFiles.find(f => item.file.endsWith(f));
243
- if (!matchedFile) continue;
244
- if (!warningsByFile[matchedFile]) {
245
- warningsByFile[matchedFile] = { warnings: 0, errors: 0 };
246
- }
247
- if (item.level === 'error') {
248
- warningsByFile[matchedFile].errors++;
249
- } else {
250
- warningsByFile[matchedFile].warnings++;
251
- }
406
+ execSync('shellcheck --version', { encoding: 'utf8', stdio: 'pipe' });
407
+ shAvailable = true;
408
+ } catch {
409
+ shAvailable = false;
410
+ }
411
+
412
+ if (shAvailable) {
413
+ // Same batching as the other tools: one argv for every shell script in the
414
+ // repo is the same platform-limit hazard, even though this repo happens to
415
+ // sit under the threshold today.
416
+ const { results, errors } = runLintInBatches(
417
+ shFiles,
418
+ batch => `shellcheck -f json ${batch.map(f => `"${f}"`).join(' ')}`,
419
+ ''
420
+ );
421
+ recordFailures('shellcheck', errors);
422
+ const warningsByFile = {};
423
+ for (const item of results) {
424
+ const matchedFile = matchResultToFile(item.file, shFiles);
425
+ if (!matchedFile) continue;
426
+ if (!warningsByFile[matchedFile]) {
427
+ warningsByFile[matchedFile] = { warnings: 0, errors: 0 };
252
428
  }
253
- for (const [file, counts] of Object.entries(warningsByFile)) {
254
- if (baseline[file]) {
255
- baseline[file].shellcheck = counts;
256
- baseline[file].totalWarnings += counts.warnings;
257
- } else {
258
- baseline[file] = {
259
- shellcheck: counts,
260
- totalWarnings: counts.warnings,
261
- lastAnalyzed: new Date().toISOString(),
262
- };
263
- }
429
+ if (item.level === 'error') {
430
+ warningsByFile[matchedFile].errors++;
431
+ } else {
432
+ warningsByFile[matchedFile].warnings++;
433
+ }
434
+ }
435
+ for (const [file, counts] of Object.entries(warningsByFile)) {
436
+ if (baseline[file]) {
437
+ baseline[file].shellcheck = counts;
438
+ baseline[file].totalWarnings += counts.warnings;
439
+ } else {
440
+ baseline[file] = {
441
+ shellcheck: counts,
442
+ totalWarnings: counts.warnings,
443
+ lastAnalyzed: new Date().toISOString(),
444
+ };
264
445
  }
265
446
  }
266
- } catch {
267
- // shellcheck unavailable — skip
268
447
  }
269
448
  }
270
449
 
@@ -468,4 +647,4 @@ Examples:
468
647
  }
469
648
  }
470
649
 
471
- module.exports = { handleBaseline, createBaseline, showBaseline, resetBaseline, diffBaseline, countBaselineByTool, compareBaselines, findShellScripts };
650
+ module.exports = { handleBaseline, createBaseline, showBaseline, resetBaseline, diffBaseline, countBaselineByTool, compareBaselines, findShellScripts, resolveLocalBin };
@@ -2,6 +2,6 @@
2
2
  "verdict": "PASS",
3
3
  "license_type": "MIT",
4
4
  "sha256": "0e7ac423bf2c6e223b7c5b156f8cf72da49d748e56a1641402c31f22ad07dbb5",
5
- "checked_at": "2026-11-16T17:40:18.009Z",
5
+ "checked_at": "2026-11-18T04:28:13.939Z",
6
6
  "source": "network"
7
7
  }
@@ -1,94 +1,96 @@
1
1
  # SRC/MOCK-POLICY KNOWLEDGE BASE
2
2
 
3
- **Generated:** 2026-11-04
4
- **Commit:** eb2097b0
5
- **Branch:** sprint/2026-11-03-02
6
- **Version:** 0.38.9.0
3
+ Mock layering for pre-push Gate M3: internal dependencies get real
4
+ implementations, external ones get mocks, and every pending dependency carries a
5
+ removal plan.
7
6
 
8
- ## OVERVIEW
9
- Mock layering policy enforcement — Gate M3 of pre-push hook. Ensures integration tests use real implementations for internal dependencies, mock external dependencies, and annotate pending mocks with removal plans. Combines project scope scanning, mock decision engine, and per-file validation into a single pipeline.
7
+ ## WHY THIS GATE EXISTS
10
8
 
11
- ## STRUCTURE
12
- ```
13
- src/mock-policy/
14
- ├── types.ts # Type definitions (MockStrategy, ProjectScope, MockDecision, etc.)
15
- ├── schema.ts # Zod schema for MockPolicyConfig validation
16
- ├── config.ts # loadMockPolicyConfig — loads from .mockpolicyrc / .xp-gate/mock-policy.yaml
17
- ├── scope-scanner.ts # scanProjectScope — classifies imports as internal/external/pending
18
- ├── mock-decision-engine.ts # MockDecisionEngine — decides mock vs real per import + test layer
19
- ├── gate-m3.ts # runGateM3 — orchestrator: filter test files → scan scope → validate
20
- └── __tests__/
21
- ├── config.test.ts # Config loader unit tests
22
- ├── scope-scanner.test.ts # Scope scanner unit + tmpdir integration tests
23
- ├── mock-decision-engine.test.ts # Decision engine unit tests
24
- └── integration.test.ts # Full pipeline integration test
25
- ```
9
+ A test that mocks the very thing it is testing always passes. That is not a weak
10
+ test — it is a test that reports success while measuring nothing, and the
11
+ failure surfaces as an incident rather than a red build. Gate M3's whole job is
12
+ to make the difference between "asserted against the real implementation" and
13
+ "asserted against my own stub" visible, because a reviewer cannot reliably tell
14
+ those apart by reading an import line.
15
+
16
+ The policy is expressed as a **decision matrix keyed by test layer**, not a list
17
+ of banned calls. The layer is what makes a mock acceptable: mocking an external
18
+ service in an integration test is correct; mocking the module under test never
19
+ is, and no amount of annotation changes that.
20
+
21
+ ## THE INVARIANTS THAT MATTER
22
+
23
+ **Test layer decides the rule.** e2e = always real. unit (lenient) = always mock
24
+ allowed, unchecked. unit (strict) = treated as integration-like. integration =
25
+ decided by dependency scope. Layer detection is delegated to
26
+ `src/mutation/detect-ai-test.ts` — deliberately not reimplemented here, so the
27
+ two gates cannot disagree about what a file is.
28
+
29
+ **Scope decides mock vs real for integration tests.** An import is internal
30
+ (resolves inside the project boundary) → must be real. External (Node builtin,
31
+ npm package outside the boundary) → mock allowed. Pending (declared but not yet
32
+ implemented) → mock allowed only with a removal plan.
33
+
34
+ **`@mock-justified` is the escape hatch for pending dependencies in integration
35
+ tests, and it demands a removal plan.** Not a suppression: a pending dependency
36
+ without one is exactly the "mock forever" state the gate exists to prevent.
37
+
38
+ **Default severity is `warning` — Gate M3 does not block a push.** This is
39
+ intentional while the matrix is being adopted; it means a green push is not
40
+ evidence that mock layering is satisfied. Read the gate's output, do not rely on
41
+ the exit status.
42
+
43
+ **Config resolves `.mockpolicyrc` (JSON) > `.xp-gate/mock-policy.yaml` (YAML) >
44
+ built-in defaults**, and is Zod-validated before use. A malformed config fails
45
+ rather than silently falling back to defaults — a gate graded against a config
46
+ nobody wrote is worse than a gate that refuses to run.
47
+
48
+ ## TRAPS
49
+
50
+ **`gate-m3.ts`'s helpers are deliberately not exported** (beyond
51
+ `runGateM`/`main`). Importing them couples callers to internals the matrix is
52
+ free to change; go through `runGateM`.
53
+
54
+ **The scanner touches the real filesystem.** There is no virtual-FS abstraction,
55
+ so scope resolution reflects the working tree — a file that exists only in the
56
+ index, or a path that requires a build step to exist, classifies as
57
+ unimplemented. Tests account for this by building real temp directories under
58
+ `os.tmpdir()`.
59
+
60
+ **`workspace:*` dependencies are skipped** when reading `package.json`, because
61
+ they are neither versioned releases nor external services.
62
+
63
+ **Do not set severity to `error` without running the full integration suite
64
+ first.** The matrix's default is `warning` precisely because the codebase's
65
+ current mock usage has not been validated against a blocking threshold.
26
66
 
27
67
  ## WHERE TO LOOK
28
- | Task | Location | Notes |
29
- |------|----------|-------|
30
- | Types/Interfaces | types.ts | MockStrategy, ProjectScope, MockPolicyConfig, MockPolicyResult |
31
- | Config loading | config.ts | .mockpolicyrc (JSON) > .xp-gate/mock-policy.yaml (YAML) > DEFAULT_CONFIG |
32
- | Schema validation | schema.ts | Zod schema for full config validation |
33
- | Scope scanning | scope-scanner.ts | scanProjectScope, classifyDependency, isExternalImport, loadExternalDependencies |
34
- | Mock decisions | mock-decision-engine.ts | MockDecisionEngine.decide() — decision matrix per test layer |
35
- | Gate runner | gate-m3.ts | runGateM3, validateFile, collectImports, detectMockUsage |
36
- | Integration tests | __tests__/integration.test.ts | End-to-end pipeline with temp project directories |
37
-
38
- ## CODE MAP
39
- | Symbol | Type | Location | Role |
40
- |--------|------|----------|------|
41
- | runGateM3 | Function | gate-m3.ts | Orchestrator: filter test files → scan scope → validate → return MockPolicyResult |
42
- | validateFile | Function | gate-m3.ts | Per-file validation: read content → detect layer → check imports → compare decision vs usage |
43
- | collectImports | Function | gate-m3.ts | Regex-based import extraction (static + dynamic) |
44
- | detectMockUsage | Function | gate-m3.ts | Checks for vi.mock/jest.mock/vi.doMock calls matching an import |
45
- | MockDecisionEngine | Class | mock-decision-engine.ts | decide(importPath, layer) → MockDecision with strategy/reason/pendingRemoval |
46
- | scanProjectScope | Function | scope-scanner.ts | Classifies imports into implemented/unimplemented/external |
47
- | classifyDependency | Function | scope-scanner.ts | Single dependency scope classification with optional existCache |
48
- | isExternalImport | Function | scope-scanner.ts | Checks Node.js builtins, bare npm packages, boundary patterns |
49
- | loadExternalDependencies | Function | scope-scanner.ts | Reads package.json dependencies (skips workspace:* protocol) |
50
- | loadMockPolicyConfig | Function | config.ts | Config loader with fallback chain and Zod validation |
51
- | detectTestLayer | Function | src/mutation/detect-ai-test.ts | Classifies test file path as unit/integration/e2e/unknown |
52
-
53
- ## CONVENTIONS
54
- - Decision matrix: e2e=always real, unit(lenient)=always mock, unit(strict)=integration-like, integration=scope-based
55
- - Pending dependencies in integration tests require `@mock-justified` annotation
56
- - Default severity: `warning` (does NOT block push)
57
- - Default boundary: `['src/**']`
58
- - Default integration policy: strict, requireRealForImplemented=true, allowExternalMock=true, requirePendingRemoval=true
59
- - Default e2e policy: strict, allowExternalMock=false, maxMockDensity=0
60
- - Unit tests with lenient policy are not checked — all mocks allowed
61
- - Config resolution: `.mockpolicyrc` (JSON) > `.xp-gate/mock-policy.yaml` (YAML) > `DEFAULT_CONFIG`
62
- - Config validated via Zod schema before use
63
-
64
- ## ANTI-PATTERNS (THIS PROJECT)
65
- - Do NOT use `as any` or `@ts-ignore` in mock-policy code
66
- - Do NOT set severity to `error` without verifying integration test suite
67
- - Do NOT disable mock checks entirely by setting zero thresholds
68
- - Do NOT import from `gate-m3.ts` private functions — they are deliberately not exported
69
-
70
- ## UNIQUE STYLES
71
- - Gate M3 is the third pre-push gate (after Gate M mutation + Gate M2 AI test detection)
72
- - Pipeline: filterTestFiles → loadConfig → collectAllImports → scanProjectScope → MockDecisionEngine → validateFile per file → aggregate violations
73
- - Uses real filesystem for scope scanning (no virtual filesystem abstraction)
74
- - Integration tests use tmpdir with real package.json + source files
75
- - Test layer detection delegates to `src/mutation/detect-ai-test.ts`
76
68
 
77
- ## COMMANDS
78
- ```bash
79
- # Run Gate M3 directly on changed files
80
- npx tsx src/mock-policy/gate-m3.ts <test-file-1> <test-file-2> ...
69
+ | Task | File |
70
+ |---|---|
71
+ | Types / interfaces | `types.ts` |
72
+ | Zod config schema | `schema.ts` |
73
+ | Config loading + fallback chain | `config.ts` |
74
+ | Internal / external / pending classification | `scope-scanner.ts` |
75
+ | Per-layer mock decision matrix | `mock-decision-engine.ts` |
76
+ | Gate orchestration, per-file validation | `gate-m3.ts` |
77
+
78
+ For the exact exported symbol names and signatures, read the files — a list here
79
+ would rot, and the file *is* the answer.
81
80
 
82
- # Run all mock-policy unit tests
83
- npx vitest run src/mock-policy/__tests__/
81
+ ## COMMANDS
84
82
 
85
- # Run just the integration test
86
- npx vitest run src/mock-policy/__tests__/integration.test.ts
83
+ ```bash
84
+ npx tsx src/mock-policy/gate-m3.ts <test-file>... # run Gate M3 on given files
85
+ npx vitest run src/mock-policy/__tests__/ # this module's tests
87
86
  ```
88
87
 
89
- ## NOTES
90
- - Gate M3 is invoked by pre-push hook after Gate M (mutation) and Gate M2 (AI test detection)
91
- - code walkthrough scope: no hard file-count or LOC threshold; large diffs require complete review or user-directed splitting, never a size-based bypass
92
- - Coverage exclude: src/mock-policy/ controlled by vitest config
93
- - The integration test creates real temporary directories under os.tmpdir()
94
- - Dependencies on: `src/mutation/detect-ai-test.ts` (detectTestLayer)
88
+ ## WHEN YOU CHANGE SOMETHING
89
+
90
+ - Adding a test layer → update the matrix in `mock-decision-engine.ts` **and**
91
+ `src/mutation/detect-ai-test.ts`; the two must agree or files classify into a
92
+ layer the matrix has no rule for.
93
+ - Changing severity → run the whole suite first; `warning` became the default
94
+ because blocking was never validated against real usage.
95
+ - Coverage exclusion for this directory is controlled by the vitest config, not
96
+ from here.