@boyingliu01/xp-gate 0.38.75 → 0.38.77

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 (111) hide show
  1. package/lib/__tests__/mirror-sync.test.js +387 -5
  2. package/lib/mattpocock-license-verdict.json +1 -1
  3. package/lib/mirror-sync.js +202 -15
  4. package/package.json +1 -1
  5. package/plugins/claude-code/.claude-plugin/plugin.json +1 -1
  6. package/plugins/claude-code/skills/delphi-review/AGENTS.md +1 -1
  7. package/plugins/claude-code/skills/sprint-flow/AGENTS.md +1 -1
  8. package/plugins/claude-code/skills/test-specification-alignment/AGENTS.md +1 -1
  9. package/plugins/dsh/lib/hooks.d.ts +10 -1
  10. package/plugins/dsh/lib/hooks.d.ts.map +1 -1
  11. package/plugins/dsh/lib/hooks.js +56 -5
  12. package/plugins/dsh/lib/index.js +6 -1
  13. package/plugins/dsh/package.json +1 -1
  14. package/plugins/dsh/skills/delphi-review/AGENTS.md +1 -1
  15. package/plugins/dsh/skills/sprint-flow/AGENTS.md +1 -1
  16. package/plugins/dsh/skills/test-specification-alignment/AGENTS.md +1 -1
  17. package/plugins/dsh/src/hooks.test.ts +70 -0
  18. package/plugins/dsh/src/hooks.ts +66 -5
  19. package/plugins/dsh/src/index.ts +6 -1
  20. package/plugins/opencode/package.json +1 -1
  21. package/plugins/opencode/skills/delphi-review/AGENTS.md +1 -1
  22. package/plugins/opencode/skills/sprint-flow/AGENTS.md +1 -1
  23. package/plugins/opencode/skills/test-specification-alignment/AGENTS.md +1 -1
  24. package/plugins/qoder/plugin.json +1 -1
  25. package/plugins/qoder/skills/delphi-review/AGENTS.md +1 -1
  26. package/plugins/qoder/skills/sprint-flow/AGENTS.md +1 -1
  27. package/plugins/qoder/skills/test-specification-alignment/AGENTS.md +1 -1
  28. package/scripts/generate-mirrors.cjs +10 -0
  29. package/skills/delphi-review/AGENTS.md +1 -1
  30. package/skills/sprint-flow/AGENTS.md +1 -1
  31. package/skills/test-specification-alignment/AGENTS.md +1 -1
  32. package/mock-policy/__tests__/config.test.ts +0 -292
  33. package/mock-policy/__tests__/gate-m3.test.ts +0 -379
  34. package/mock-policy/__tests__/integration.test.ts +0 -600
  35. package/mock-policy/__tests__/mock-decision-engine.test.ts +0 -231
  36. package/mock-policy/__tests__/schema.test.ts +0 -239
  37. package/mock-policy/__tests__/scope-scanner.test.ts +0 -541
  38. package/mutation/__tests__/detect-ai-test.test.ts +0 -152
  39. package/mutation/__tests__/gate-m-survivors.test.ts +0 -167
  40. package/mutation/__tests__/gate-m.test.ts +0 -246
  41. package/mutation/__tests__/go-mutant-runner.test.ts +0 -288
  42. package/mutation/__tests__/gremlins-runner.test.ts +0 -167
  43. package/mutation/__tests__/init-baseline.test.ts +0 -347
  44. package/mutation/__tests__/mutation-mirror.test.ts +0 -49
  45. package/mutation/__tests__/mutmut-runner.test.ts +0 -1049
  46. package/mutation/__tests__/pitest-gradle-availability.test.ts +0 -74
  47. package/mutation/__tests__/pitest-runner.test.ts +0 -574
  48. package/mutation/__tests__/runners-index.test.ts +0 -162
  49. package/mutation/__tests__/stryker-runner.test.ts +0 -455
  50. package/mutation/__tests__/test-filter-parity.test.ts +0 -40
  51. package/mutation/__tests__/update-baseline.test.ts +0 -395
  52. package/principles/__tests__/adapter-metrics.test.ts +0 -292
  53. package/principles/__tests__/analyze-read-failure.test.ts +0 -70
  54. package/principles/__tests__/analyzer.test.ts +0 -367
  55. package/principles/__tests__/baseline-entry-total-warnings.test.ts +0 -76
  56. package/principles/__tests__/baseline-prune-timeout.test.ts +0 -71
  57. package/principles/__tests__/baseline-prune.test.ts +0 -399
  58. package/principles/__tests__/baseline-storage.test.ts +0 -188
  59. package/principles/__tests__/baseline.test.ts +0 -330
  60. package/principles/__tests__/boy-scout-init-baseline.test.ts +0 -167
  61. package/principles/__tests__/boy-scout-integration.test.ts +0 -355
  62. package/principles/__tests__/boy-scout.test.ts +0 -893
  63. package/principles/__tests__/cli-files-separators.test.ts +0 -69
  64. package/principles/__tests__/config-arch-group.test.ts +0 -106
  65. package/principles/__tests__/config-enforcement.test.ts +0 -470
  66. package/principles/__tests__/config-git-timeout.test.ts +0 -66
  67. package/principles/__tests__/config-merge-warnings.test.ts +0 -148
  68. package/principles/__tests__/config.test.ts +0 -78
  69. package/principles/__tests__/direct-execution.test.ts +0 -187
  70. package/principles/__tests__/index.test.ts +0 -94
  71. package/principles/__tests__/issue-587-java-member-count.test.ts +0 -279
  72. package/principles/__tests__/issue-588-lsp-java-false-positives.test.ts +0 -213
  73. package/principles/__tests__/lint-baseline.test.ts +0 -314
  74. package/principles/__tests__/many-exports-reexport.test.ts +0 -40
  75. package/principles/__tests__/reporter.test.ts +0 -660
  76. package/principles/__tests__/types.test.ts +0 -103
  77. package/principles/__tests__/warnings-baseline-budgets.test.ts +0 -74
  78. package/principles/adapters/__tests__/base.test.ts +0 -95
  79. package/principles/adapters/__tests__/cpp-code-block.test.ts +0 -123
  80. package/principles/adapters/__tests__/cpp-scanner-equivalence.test.ts +0 -67
  81. package/principles/adapters/__tests__/cpp.test.ts +0 -290
  82. package/principles/adapters/__tests__/dart.test.ts +0 -84
  83. package/principles/adapters/__tests__/go.test.ts +0 -68
  84. package/principles/adapters/__tests__/java.test.ts +0 -385
  85. package/principles/adapters/__tests__/kotlin.test.ts +0 -76
  86. package/principles/adapters/__tests__/objectivec.test.ts +0 -453
  87. package/principles/adapters/__tests__/python.test.ts +0 -84
  88. package/principles/adapters/__tests__/swift.test.ts +0 -68
  89. package/principles/adapters/__tests__/typescript-block-comment-lines.test.ts +0 -53
  90. package/principles/adapters/__tests__/typescript-masking.test.ts +0 -96
  91. package/principles/adapters/__tests__/typescript.test.ts +0 -116
  92. package/principles/rules/__tests__/clean-code/code-duplication.test.ts +0 -85
  93. package/principles/rules/__tests__/clean-code/deep-nesting.test.ts +0 -73
  94. package/principles/rules/__tests__/clean-code/god-class.test.ts +0 -109
  95. package/principles/rules/__tests__/clean-code/large-file.test.ts +0 -73
  96. package/principles/rules/__tests__/clean-code/long-function.test.ts +0 -81
  97. package/principles/rules/__tests__/clean-code/magic-numbers.test.ts +0 -68
  98. package/principles/rules/__tests__/clean-code/many-exports.test.ts +0 -123
  99. package/principles/rules/__tests__/clean-code/missing-error-handling.test.ts +0 -171
  100. package/principles/rules/__tests__/clean-code/too-many-params.test.ts +0 -58
  101. package/principles/rules/__tests__/clean-code/unused-imports.test.ts +0 -107
  102. package/principles/rules/__tests__/index.test.ts +0 -49
  103. package/principles/rules/__tests__/solid/dip.test.ts +0 -119
  104. package/principles/rules/__tests__/solid/isp.test.ts +0 -58
  105. package/principles/rules/__tests__/solid/issue-588-lsp-base-contract.test.ts +0 -252
  106. package/principles/rules/__tests__/solid/lsp.test.ts +0 -186
  107. package/principles/rules/__tests__/solid/ocp.test.ts +0 -67
  108. package/principles/rules/__tests__/solid/srp.test.ts +0 -87
  109. package/principles/rules/arch/__tests__/dependency.test.ts +0 -180
  110. package/principles/rules/arch/__tests__/naming.test.ts +0 -133
  111. package/principles/rules/arch/__tests__/shared.test.ts +0 -113
@@ -1,395 +0,0 @@
1
- /**
2
- * @test update-baseline.ts - Mutation baseline update CLI
3
- * @intent Verify parseArgs, updateBaseline, removeDeletedFiles, and readBaseline
4
- * work correctly through the module's side effects
5
- * @covers REQ-MUT-001 AC-004 (baseline update from mutation scores)
6
- */
7
-
8
- import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
9
-
10
- vi.mock('fs/promises', () => ({
11
- default: {
12
- readFile: vi.fn(),
13
- writeFile: vi.fn(),
14
- access: vi.fn()
15
- },
16
- readFile: vi.fn(),
17
- writeFile: vi.fn(),
18
- access: vi.fn()
19
- }));
20
-
21
- const mockFs = await import('fs/promises');
22
-
23
- interface MockBaseline {
24
- version: string;
25
- generatedAt: string;
26
- source: 'local' | 'ci';
27
- scores: Record<string, { score: number; mutants: number; killed: number; survived: number }>;
28
- }
29
-
30
- function makeBaseline(overrides: Partial<MockBaseline> = {}): MockBaseline {
31
- return {
32
- version: '1.0.0',
33
- generatedAt: '2024-01-01T00:00:00.000Z',
34
- source: 'local',
35
- scores: {},
36
- ...overrides
37
- };
38
- }
39
-
40
- describe('update-baseline.ts - Mutation Baseline Update CLI', () => {
41
- let originalArgv: string[];
42
- let originalExit: typeof process.exit;
43
- let originalCwd: typeof process.cwd;
44
- let consoleLogSpy: any;
45
- let consoleErrorSpy: any;
46
- let exitCode: number | undefined;
47
-
48
- beforeEach(() => {
49
- originalArgv = process.argv;
50
- originalExit = process.exit;
51
- originalCwd = process.cwd;
52
-
53
- consoleLogSpy = vi.spyOn(console, 'log').mockImplementation(() => undefined);
54
- consoleErrorSpy = vi.spyOn(console, 'error').mockImplementation(() => undefined);
55
-
56
- process.exit = ((code?: number) => {
57
- exitCode = code;
58
- return undefined as never;
59
- }) as typeof process.exit;
60
-
61
- process.cwd = () => '/fake/project';
62
-
63
- vi.resetModules();
64
- vi.clearAllMocks();
65
- exitCode = undefined;
66
- });
67
-
68
- afterEach(() => {
69
- process.argv = originalArgv;
70
- process.exit = originalExit;
71
- process.cwd = originalCwd;
72
- consoleLogSpy.mockRestore();
73
- consoleErrorSpy.mockRestore();
74
- });
75
-
76
- async function importModule(): Promise<void> {
77
- await import('../update-baseline');
78
- // Allow the main() promise chain to settle
79
- await new Promise((resolve) => setTimeout(resolve, 10));
80
- }
81
-
82
- describe('parseArgs', () => {
83
- it('should parse valid --scores argument with single file', async () => {
84
- process.argv = ['node', 'update-baseline.js', '--scores', 'src/foo.ts:75.5'];
85
- const baseline = makeBaseline();
86
- (mockFs.default.readFile as ReturnType<typeof vi.fn>).mockResolvedValue(
87
- JSON.stringify(baseline)
88
- );
89
- (mockFs.default.access as ReturnType<typeof vi.fn>).mockResolvedValue(undefined);
90
- (mockFs.default.writeFile as ReturnType<typeof vi.fn>).mockResolvedValue(undefined);
91
-
92
- await importModule();
93
-
94
- expect(exitCode).toBeUndefined();
95
- expect(mockFs.default.writeFile).toHaveBeenCalled();
96
- const written = JSON.parse(
97
- (mockFs.default.writeFile as ReturnType<typeof vi.fn>).mock.calls[0][1] as string
98
- );
99
- expect(written.scores['src/foo.ts'].score).toBe(75.5);
100
- });
101
-
102
- it('should parse multiple comma-separated scores', async () => {
103
- process.argv = [
104
- 'node',
105
- 'update-baseline.js',
106
- '--scores',
107
- 'src/a.ts:80.0,src/b.ts:65.3,src/c.ts:92.7'
108
- ];
109
- const baseline = makeBaseline();
110
- (mockFs.default.readFile as ReturnType<typeof vi.fn>).mockResolvedValue(
111
- JSON.stringify(baseline)
112
- );
113
- (mockFs.default.access as ReturnType<typeof vi.fn>).mockResolvedValue(undefined);
114
- (mockFs.default.writeFile as ReturnType<typeof vi.fn>).mockResolvedValue(undefined);
115
-
116
- await importModule();
117
-
118
- const written = JSON.parse(
119
- (mockFs.default.writeFile as ReturnType<typeof vi.fn>).mock.calls[0][1] as string
120
- );
121
- expect(Object.keys(written.scores)).toHaveLength(3);
122
- expect(written.scores['src/a.ts'].score).toBe(80.0);
123
- expect(written.scores['src/b.ts'].score).toBe(65.3);
124
- expect(written.scores['src/c.ts'].score).toBe(92.7);
125
- });
126
-
127
- it('should throw and exit 1 when --scores is missing', async () => {
128
- process.argv = ['node', 'update-baseline.js'];
129
-
130
- await importModule();
131
-
132
- expect(exitCode).toBe(1);
133
- expect(consoleErrorSpy).toHaveBeenCalledWith(
134
- expect.stringContaining('Missing required argument: --scores')
135
- );
136
- });
137
-
138
- it('should throw and exit 1 when score format is invalid (missing colon)', async () => {
139
- process.argv = ['node', 'update-baseline.js', '--scores', 'src/foo.ts'];
140
-
141
- await importModule();
142
-
143
- expect(exitCode).toBe(1);
144
- expect(consoleErrorSpy).toHaveBeenCalledWith(
145
- expect.stringContaining('Invalid score format')
146
- );
147
- });
148
-
149
- it('should throw and exit 1 when score value is NaN', async () => {
150
- process.argv = ['node', 'update-baseline.js', '--scores', 'src/foo.ts:notanumber'];
151
-
152
- await importModule();
153
-
154
- expect(exitCode).toBe(1);
155
- expect(consoleErrorSpy).toHaveBeenCalledWith(
156
- expect.stringContaining('Invalid score value')
157
- );
158
- });
159
-
160
- it('should throw and exit 1 when score is out of range (>100)', async () => {
161
- process.argv = ['node', 'update-baseline.js', '--scores', 'src/foo.ts:150'];
162
-
163
- await importModule();
164
-
165
- expect(exitCode).toBe(1);
166
- expect(consoleErrorSpy).toHaveBeenCalledWith(
167
- expect.stringContaining('Invalid score value')
168
- );
169
- });
170
-
171
- it('should throw and exit 1 when score is negative', async () => {
172
- process.argv = ['node', 'update-baseline.js', '--scores', 'src/foo.ts:-5'];
173
-
174
- await importModule();
175
-
176
- expect(exitCode).toBe(1);
177
- expect(consoleErrorSpy).toHaveBeenCalledWith(
178
- expect.stringContaining('Invalid score value')
179
- );
180
- });
181
- });
182
-
183
- describe('updateBaseline (via module side effects)', () => {
184
- it('should merge new scores into existing baseline entries', async () => {
185
- process.argv = ['node', 'update-baseline.js', '--scores', 'src/existing.ts:88.5'];
186
- const baseline = makeBaseline({
187
- scores: {
188
- 'src/existing.ts': { score: 50.0, mutants: 10, killed: 5, survived: 5 }
189
- }
190
- });
191
- (mockFs.default.readFile as ReturnType<typeof vi.fn>).mockResolvedValue(
192
- JSON.stringify(baseline)
193
- );
194
- (mockFs.default.access as ReturnType<typeof vi.fn>).mockResolvedValue(undefined);
195
- (mockFs.default.writeFile as ReturnType<typeof vi.fn>).mockResolvedValue(undefined);
196
-
197
- await importModule();
198
-
199
- const written = JSON.parse(
200
- (mockFs.default.writeFile as ReturnType<typeof vi.fn>).mock.calls[0][1] as string
201
- );
202
- // Score should be updated
203
- expect(written.scores['src/existing.ts'].score).toBe(88.5);
204
- // Existing metadata should be preserved
205
- expect(written.scores['src/existing.ts'].mutants).toBe(10);
206
- expect(written.scores['src/existing.ts'].killed).toBe(5);
207
- expect(written.scores['src/existing.ts'].survived).toBe(5);
208
- });
209
-
210
- it('should add new file entries with zeroed metadata', async () => {
211
- process.argv = ['node', 'update-baseline.js', '--scores', 'src/new.ts:72.0'];
212
- const baseline = makeBaseline({
213
- scores: {
214
- 'src/old.ts': { score: 60.0, mutants: 8, killed: 4, survived: 4 }
215
- }
216
- });
217
- (mockFs.default.readFile as ReturnType<typeof vi.fn>).mockResolvedValue(
218
- JSON.stringify(baseline)
219
- );
220
- (mockFs.default.access as ReturnType<typeof vi.fn>).mockResolvedValue(undefined);
221
- (mockFs.default.writeFile as ReturnType<typeof vi.fn>).mockResolvedValue(undefined);
222
-
223
- await importModule();
224
-
225
- const written = JSON.parse(
226
- (mockFs.default.writeFile as ReturnType<typeof vi.fn>).mock.calls[0][1] as string
227
- );
228
- // #544: a new entry built from a score alone must NOT be seeded with
229
- // mutants/killed/survived = 0. This assertion previously pinned those
230
- // zeros as the expected behaviour, which made "nobody measured this file"
231
- // indistinguishable from "measured, zero survivors" in every baseline
232
- // written from the CLI. The fields are omitted instead.
233
- expect(written.scores['src/new.ts']).toEqual({
234
- score: 72.0,
235
- });
236
- expect(written.scores['src/new.ts'].mutants).toBeUndefined();
237
- expect(written.scores['src/new.ts'].survived).toBeUndefined();
238
- // Old entry should still be present
239
- expect(written.scores['src/old.ts'].score).toBe(60.0);
240
- });
241
-
242
- it('should update generatedAt timestamp', async () => {
243
- process.argv = ['node', 'update-baseline.js', '--scores', 'src/foo.ts:50.0'];
244
- const baseline = makeBaseline({ generatedAt: '2020-01-01T00:00:00.000Z' });
245
- (mockFs.default.readFile as ReturnType<typeof vi.fn>).mockResolvedValue(
246
- JSON.stringify(baseline)
247
- );
248
- (mockFs.default.access as ReturnType<typeof vi.fn>).mockResolvedValue(undefined);
249
- (mockFs.default.writeFile as ReturnType<typeof vi.fn>).mockResolvedValue(undefined);
250
-
251
- await importModule();
252
-
253
- const written = JSON.parse(
254
- (mockFs.default.writeFile as ReturnType<typeof vi.fn>).mock.calls[0][1] as string
255
- );
256
- expect(written.generatedAt).not.toBe('2020-01-01T00:00:00.000Z');
257
- // Should be a valid ISO date string
258
- expect(new Date(written.generatedAt).toISOString()).toBe(written.generatedAt);
259
- });
260
-
261
- it('should round score to 1 decimal place', async () => {
262
- process.argv = ['node', 'update-baseline.js', '--scores', 'src/foo.ts:66.66666'];
263
- const baseline = makeBaseline();
264
- (mockFs.default.readFile as ReturnType<typeof vi.fn>).mockResolvedValue(
265
- JSON.stringify(baseline)
266
- );
267
- (mockFs.default.access as ReturnType<typeof vi.fn>).mockResolvedValue(undefined);
268
- (mockFs.default.writeFile as ReturnType<typeof vi.fn>).mockResolvedValue(undefined);
269
-
270
- await importModule();
271
-
272
- const written = JSON.parse(
273
- (mockFs.default.writeFile as ReturnType<typeof vi.fn>).mock.calls[0][1] as string
274
- );
275
- expect(written.scores['src/foo.ts'].score).toBe(66.7);
276
- });
277
- });
278
-
279
- describe('removeDeletedFiles (via module side effects)', () => {
280
- it('should remove files that no longer exist on disk', async () => {
281
- process.argv = ['node', 'update-baseline.js', '--scores', 'src/keep.ts:80.0'];
282
- const baseline = makeBaseline({
283
- scores: {
284
- 'src/keep.ts': { score: 70.0, mutants: 10, killed: 7, survived: 3 },
285
- 'src/deleted.ts': { score: 50.0, mutants: 5, killed: 2, survived: 3 }
286
- }
287
- });
288
- (mockFs.default.readFile as ReturnType<typeof vi.fn>).mockResolvedValue(
289
- JSON.stringify(baseline)
290
- );
291
- (mockFs.default.access as ReturnType<typeof vi.fn>).mockImplementation(
292
- (filePath: string) => {
293
- if (filePath.includes('deleted.ts')) {
294
- return Promise.reject(new Error('ENOENT'));
295
- }
296
- return Promise.resolve(undefined);
297
- }
298
- );
299
- (mockFs.default.writeFile as ReturnType<typeof vi.fn>).mockResolvedValue(undefined);
300
-
301
- await importModule();
302
-
303
- const written = JSON.parse(
304
- (mockFs.default.writeFile as ReturnType<typeof vi.fn>).mock.calls[0][1] as string
305
- );
306
- expect(written.scores['src/keep.ts']).toBeDefined();
307
- expect(written.scores['src/deleted.ts']).toBeUndefined();
308
- expect(consoleLogSpy).toHaveBeenCalledWith(
309
- expect.stringContaining('Removing deleted file from baseline: src/deleted.ts')
310
- );
311
- });
312
-
313
- it('should keep all files when they all exist on disk', async () => {
314
- process.argv = ['node', 'update-baseline.js', '--scores', 'src/a.ts:90.0'];
315
- const baseline = makeBaseline({
316
- scores: {
317
- 'src/a.ts': { score: 80.0, mutants: 10, killed: 8, survived: 2 },
318
- 'src/b.ts': { score: 70.0, mutants: 8, killed: 5, survived: 3 }
319
- }
320
- });
321
- (mockFs.default.readFile as ReturnType<typeof vi.fn>).mockResolvedValue(
322
- JSON.stringify(baseline)
323
- );
324
- (mockFs.default.access as ReturnType<typeof vi.fn>).mockResolvedValue(undefined);
325
- (mockFs.default.writeFile as ReturnType<typeof vi.fn>).mockResolvedValue(undefined);
326
-
327
- await importModule();
328
-
329
- const written = JSON.parse(
330
- (mockFs.default.writeFile as ReturnType<typeof vi.fn>).mock.calls[0][1] as string
331
- );
332
- expect(Object.keys(written.scores)).toHaveLength(2);
333
- });
334
- });
335
-
336
- describe('readBaseline (via module side effects)', () => {
337
- it('should fail with error when baseline file does not exist', async () => {
338
- process.argv = ['node', 'update-baseline.js', '--scores', 'src/foo.ts:50.0'];
339
- (mockFs.default.readFile as ReturnType<typeof vi.fn>).mockRejectedValue(
340
- new Error('ENOENT: no such file')
341
- );
342
-
343
- await importModule();
344
-
345
- expect(exitCode).toBe(1);
346
- expect(consoleErrorSpy).toHaveBeenCalledWith(
347
- expect.stringContaining('Failed to read baseline file')
348
- );
349
- });
350
-
351
- it('should fail with error when baseline file contains invalid JSON', async () => {
352
- process.argv = ['node', 'update-baseline.js', '--scores', 'src/foo.ts:50.0'];
353
- (mockFs.default.readFile as ReturnType<typeof vi.fn>).mockResolvedValue(
354
- 'not-valid-json{{{'
355
- );
356
-
357
- await importModule();
358
-
359
- expect(exitCode).toBe(1);
360
- expect(consoleErrorSpy).toHaveBeenCalledWith(
361
- expect.stringContaining('Failed to read baseline file')
362
- );
363
- });
364
- });
365
-
366
- describe('end-to-end output', () => {
367
- it('should log per-file scores and total file count', async () => {
368
- process.argv = [
369
- 'node',
370
- 'update-baseline.js',
371
- '--scores',
372
- 'src/a.ts:80.0,src/b.ts:60.0'
373
- ];
374
- const baseline = makeBaseline();
375
- (mockFs.default.readFile as ReturnType<typeof vi.fn>).mockResolvedValue(
376
- JSON.stringify(baseline)
377
- );
378
- (mockFs.default.access as ReturnType<typeof vi.fn>).mockResolvedValue(undefined);
379
- (mockFs.default.writeFile as ReturnType<typeof vi.fn>).mockResolvedValue(undefined);
380
-
381
- await importModule();
382
-
383
- const allLogs = consoleLogSpy.mock.calls.map((c: unknown[]) => c[0]);
384
- expect(allLogs).toEqual(
385
- expect.arrayContaining([
386
- 'Reading existing mutation baseline...',
387
- 'Updating 2 file score(s)...',
388
- 'Checking for deleted files...',
389
- 'Total files: 2'
390
- ])
391
- );
392
- expect(allLogs).toEqual(expect.arrayContaining([' src/a.ts: 80%', ' src/b.ts: 60%']));
393
- });
394
- });
395
- });
@@ -1,292 +0,0 @@
1
- /**
2
- * @test REQ-DSH-015
3
- * @intent 验证 TypeScriptAdapter 为各规则提供其所需度量字段:fix #446 之前,
4
- * createCodeMatch() 只返回 {name,type,line,code},而规则读取
5
- * length / paramCount / nestingDepth / methodCount / hasTryCatch,
6
- * 导致 14 条规则里 12 条在 TypeScript 上结构性无法触发(Gate 4 形同虚设)
7
- * @covers AC-DSH-015-01
8
- *
9
- * Mock-first per src/principles/AGENTS.md: inline fixture, no separate files.
10
- */
11
-
12
- import { describe, it, expect, vi, type Mock } from 'vitest';
13
- import { TypeScriptAdapter } from '../adapters/typescript';
14
-
15
- vi.mock('fs', () => ({
16
- readFileSync: vi.fn(),
17
- existsSync: vi.fn(() => true),
18
- }));
19
-
20
- import { readFileSync } from 'fs';
21
-
22
- const LONG_BODY = Array.from({ length: 60 }, (_, i) => ` const v${i} = ${i};`).join('\n');
23
-
24
- const SAMPLE = `
25
- import { helper } from './helper';
26
-
27
- export function eightParams(a: number, b: number, c: number, d: number, e: number, f: number, g: number, h: number) {
28
- return a + b + c + d + e + f + g + h;
29
- }
30
-
31
- export function longOne() {
32
- ${LONG_BODY}
33
- return 0;
34
- }
35
-
36
- export function deeplyNested(a: number) {
37
- if (a > 0) {
38
- if (a > 1) {
39
- if (a > 2) {
40
- if (a > 3) {
41
- if (a > 4) {
42
- return 'deep';
43
- }
44
- }
45
- }
46
- }
47
- }
48
- return 'shallow';
49
- }
50
-
51
- export function rawIo() {
52
- return readFileSync('/tmp/x', 'utf-8');
53
- }
54
-
55
- export function guardedIo() {
56
- try {
57
- return readFileSync('/tmp/x', 'utf-8');
58
- } catch (e) {
59
- return '';
60
- }
61
- }
62
-
63
- export const arrowFn = (x: number, y: number) => x + y;
64
-
65
- export class MegaService {
66
- aMethod() { return 1; }
67
- m1() { return 1; } m2() { return 1; } m3() { return 1; } m4() { return 1; }
68
- m5() { return 1; } m6() { return 1; } m7() { return 1; } m8() { return 1; }
69
- m9() { return 1; } m10() { return 1; } m11() { return 1; } m12() { return 1; }
70
- m13() { return 1; } m14() { return 1; } m15() { return 1; }
71
- }
72
- `;
73
-
74
- interface FnInfo {
75
- name: string;
76
- startLine?: number;
77
- line?: number;
78
- length?: number;
79
- paramCount?: number;
80
- nestingDepth?: number;
81
- hasTryCatch?: boolean;
82
- ioOperations?: string[];
83
- }
84
-
85
- interface ClsInfo {
86
- name: string;
87
- methodCount?: number;
88
- line?: number;
89
- }
90
-
91
- function adapterFor(content = SAMPLE): TypeScriptAdapter {
92
- (readFileSync as Mock).mockReturnValue(content);
93
- return new TypeScriptAdapter('sample.ts');
94
- }
95
-
96
- describe('TypeScriptAdapter metric extraction (#446)', () => {
97
- describe('extractFunctions', () => {
98
- it('reports paramCount for every function', () => {
99
- const fns = adapterFor().extractFunctions() as FnInfo[];
100
- const eight = fns.find(f => f.name === 'eightParams');
101
- expect(eight).toBeDefined();
102
- expect(eight?.paramCount).toBe(8);
103
- });
104
-
105
- it('reports length (body span) for every function', () => {
106
- const fns = adapterFor().extractFunctions() as FnInfo[];
107
- const long = fns.find(f => f.name === 'longOne');
108
- expect(long).toBeDefined();
109
- // > 50 lines is the long-function threshold; assert it is measured at all.
110
- expect(long?.length).toBeGreaterThan(50);
111
- });
112
-
113
- it('reports nestingDepth for every function', () => {
114
- const fns = adapterFor().extractFunctions() as FnInfo[];
115
- const deep = fns.find(f => f.name === 'deeplyNested');
116
- expect(deep).toBeDefined();
117
- expect(deep?.nestingDepth).toBeGreaterThanOrEqual(5);
118
- });
119
-
120
- it('reports hasTryCatch for unguarded and guarded IO', () => {
121
- const fns = adapterFor().extractFunctions() as FnInfo[];
122
- const io = fns.find(f => f.name === 'rawIo');
123
- expect(io).toBeDefined();
124
- expect(io?.hasTryCatch).toBe(false);
125
-
126
- const guarded = fns.find(f => f.name === 'guardedIo');
127
- expect(guarded).toBeDefined();
128
- expect(guarded?.hasTryCatch).toBe(true);
129
- });
130
-
131
- it('reports ioOperations for IO-performing functions', () => {
132
- const fns = adapterFor().extractFunctions() as FnInfo[];
133
- const io = fns.find(f => f.name === 'rawIo');
134
- expect(io?.ioOperations?.length ?? 0).toBeGreaterThan(0);
135
- });
136
-
137
- it('still reports name / line for every function', () => {
138
- const fns = adapterFor().extractFunctions() as FnInfo[];
139
- expect(fns.length).toBeGreaterThan(0);
140
- for (const f of fns) {
141
- expect(f.name).toBeTruthy();
142
- expect(f.line).toBeGreaterThan(0);
143
- }
144
- });
145
-
146
- it('finds arrow functions and class methods, not only `function` declarations', () => {
147
- const fns = adapterFor().extractFunctions() as FnInfo[];
148
- const names = fns.map(f => f.name);
149
- // Arrow consts and class methods are the dominant modern TS forms; the old
150
- // regex only matched the literal `function` keyword.
151
- expect(names).toContain('arrowFn');
152
- expect(names).toContain('aMethod');
153
- });
154
- });
155
-
156
- describe('extractClasses', () => {
157
- it('reports methodCount per class', () => {
158
- const classes = adapterFor().extractClasses() as ClsInfo[];
159
- const mega = classes.find(c => c.name === 'MegaService');
160
- expect(mega).toBeDefined();
161
- expect(mega?.methodCount).toBeGreaterThanOrEqual(15);
162
- });
163
- });
164
-
165
- describe('imports', () => {
166
- interface ImportInfo {
167
- name?: string;
168
- line?: number;
169
- used?: boolean;
170
- type?: string;
171
- }
172
-
173
- it('returns objects, not bare strings (the rule reads .name/.used)', () => {
174
- const imports = (adapterFor() as unknown as { imports: ImportInfo[] }).imports;
175
- expect(Array.isArray(imports)).toBe(true);
176
- expect(imports.length).toBeGreaterThan(0);
177
- for (const imp of imports) {
178
- expect(typeof imp).toBe('object');
179
- // Never leak `undefined` as a name -- it renders straight into the message.
180
- expect(imp.name).toBeTruthy();
181
- expect(imp.name).not.toBe('undefined');
182
- expect(imp.line).toBeGreaterThan(0);
183
- }
184
- });
185
-
186
- it('marks a genuinely unused import as unused', () => {
187
- const imports = (adapterFor() as unknown as { imports: ImportInfo[] }).imports;
188
- const helper = imports.find(i => i.name === 'helper');
189
- expect(helper).toBeDefined();
190
- // `helper` is imported but never referenced in SAMPLE.
191
- expect(helper?.used).toBe(false);
192
- });
193
-
194
- it('marks a referenced import as used', () => {
195
- const content = `
196
- import { readFileSync } from 'fs';
197
- export function go() { return readFileSync('/tmp/x', 'utf-8'); }
198
- `;
199
- const imports = (adapterFor(content) as unknown as { imports: ImportInfo[] }).imports;
200
- const rfs = imports.find(i => i.name === 'readFileSync');
201
- expect(rfs).toBeDefined();
202
- expect(rfs?.used).toBe(true);
203
- });
204
- });
205
-
206
- describe('extract (magic numbers, #446)', () => {
207
- it('returns {value,line} objects and ignores comments/strings', () => {
208
- const content = `
209
- // 999 should not count (comment)
210
- const s = "1234 should not count (string)";
211
- export function f() { return 12345; }
212
- `;
213
- const nums = (adapterFor(content) as unknown as {
214
- extract: () => Array<{ value: number; line: number }>;
215
- }).extract();
216
- const values = nums.map(n => n.value);
217
- expect(values).toContain(12345);
218
- expect(values).not.toContain(999);
219
- expect(values).not.toContain(1234);
220
- for (const n of nums) expect(n.line).toBeGreaterThan(0);
221
- });
222
-
223
- /**
224
- * @test REQ-DSH-018
225
- * @intent 验证「命名常量的初始化值」不被当作 magic number:规则的修复建议
226
- * 就是「改用命名常量」,若常量本身仍被标记,该违规永远无法消除
227
- * @covers AC-DSH-018-01
228
- */
229
- it('skips the initializer of a named constant but still reports bare literals', () => {
230
- // Fixtures are bare fragments: no `export`, so this file does not itself
231
- // trip the many-exports rule that the adapter under test is meant to flag.
232
- const content = `
233
- const RENAME_PARTS = 3;
234
- const BUDGET: number = 5;
235
- function f(): number {
236
- return 137;
237
- }
238
- `;
239
- const nums = (adapterFor(content) as unknown as {
240
- extract: () => Array<{ value: number; line: number }>;
241
- }).extract();
242
- const values = nums.map(n => n.value);
243
-
244
- // The rule asks for named constants, so the constants must not be flagged.
245
- expect(values).not.toContain(3);
246
- expect(values).not.toContain(5);
247
- // A bare literal in a body is the actual target and must still be reported.
248
- expect(values).toContain(137);
249
- });
250
-
251
- it('still reports a number assigned to a non-constant binding', () => {
252
- // Only `const`/`readonly` declarations are exempt; `let x = 99` is not.
253
- const content = `
254
- function f(): number {
255
- let x = 99;
256
- return x;
257
- }
258
- `;
259
- const nums = (adapterFor(content) as unknown as {
260
- extract: () => Array<{ value: number; line: number }>;
261
- }).extract();
262
- expect(nums.map(n => n.value)).toContain(99);
263
- });
264
- });
265
-
266
- describe('extractInterfaces (ISP, #446)', () => {
267
- it('reports interface names and methodCount', () => {
268
- const content = `
269
- export interface Worker {
270
- run(): void;
271
- stop(): void;
272
- }
273
- `;
274
- const ifaces = (adapterFor(content) as unknown as {
275
- extractInterfaces: () => Array<{ name: string; methodCount: number }>;
276
- }).extractInterfaces();
277
- const worker = ifaces.find(i => i.name === 'Worker');
278
- expect(worker).toBeDefined();
279
- expect(worker?.methodCount).toBe(2);
280
- });
281
- });
282
-
283
- describe('no control-flow false positives', () => {
284
- it('does not report `if` / `for` / `while` as functions', () => {
285
- const fns = adapterFor().extractFunctions() as FnInfo[];
286
- const names = fns.map(f => f.name);
287
- for (const kw of ['if', 'for', 'while', 'switch', 'catch', 'return']) {
288
- expect(names).not.toContain(kw);
289
- }
290
- });
291
- });
292
- });