@boyingliu01/xp-gate 0.38.76 → 0.38.78

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__/gate2-verdict.test.js +58 -1
  2. package/lib/__tests__/mirror-sync.test.js +387 -5
  3. package/lib/gate-runner.js +88 -9
  4. package/lib/mattpocock-license-verdict.json +1 -1
  5. package/lib/mirror-sync.js +202 -15
  6. package/package.json +1 -1
  7. package/plugins/claude-code/.claude-plugin/plugin.json +1 -1
  8. package/plugins/claude-code/skills/delphi-review/AGENTS.md +1 -1
  9. package/plugins/claude-code/skills/sprint-flow/AGENTS.md +1 -1
  10. package/plugins/claude-code/skills/sprint-flow/references/phase-2-design.md +62 -2
  11. package/plugins/claude-code/skills/test-specification-alignment/AGENTS.md +1 -1
  12. package/plugins/dsh/package.json +1 -1
  13. package/plugins/dsh/skills/delphi-review/AGENTS.md +1 -1
  14. package/plugins/dsh/skills/sprint-flow/AGENTS.md +1 -1
  15. package/plugins/dsh/skills/sprint-flow/references/phase-2-design.md +62 -2
  16. package/plugins/dsh/skills/test-specification-alignment/AGENTS.md +1 -1
  17. package/plugins/opencode/package.json +1 -1
  18. package/plugins/opencode/skills/delphi-review/AGENTS.md +1 -1
  19. package/plugins/opencode/skills/sprint-flow/AGENTS.md +1 -1
  20. package/plugins/opencode/skills/sprint-flow/references/phase-2-design.md +62 -2
  21. package/plugins/opencode/skills/test-specification-alignment/AGENTS.md +1 -1
  22. package/plugins/qoder/plugin.json +1 -1
  23. package/plugins/qoder/skills/delphi-review/AGENTS.md +1 -1
  24. package/plugins/qoder/skills/sprint-flow/AGENTS.md +1 -1
  25. package/plugins/qoder/skills/sprint-flow/references/phase-2-design.md +62 -2
  26. package/plugins/qoder/skills/test-specification-alignment/AGENTS.md +1 -1
  27. package/scripts/generate-mirrors.cjs +10 -0
  28. package/skills/delphi-review/AGENTS.md +1 -1
  29. package/skills/sprint-flow/AGENTS.md +1 -1
  30. package/skills/sprint-flow/references/phase-2-design.md +62 -2
  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,69 +0,0 @@
1
- /**
2
- * @test REQ-623
3
- * @intent `--files` must accept the shapes a shell actually produces. CI passed
4
- * `--files "$SRC_FILES"` -- one argument containing newline-separated
5
- * paths -- and parseArgs split on spaces only, so the whole blob became
6
- * a single impossible path. The run then had nothing to analyse and fell
7
- * through to the console/empty path, writing "✓ No violations found"
8
- * into a file named principles.sarif. The step exited 0, so for months
9
- * the GitHub Security tab received a text file where SARIF was expected.
10
- *
11
- * These tests pin the separator handling, not one call site: a fix that
12
- * only changes the workflow leaves the next caller to hit the same trap.
13
- * @covers AC-623-01, AC-623-02, AC-623-03
14
- */
15
-
16
- import { describe, it, expect } from 'vitest';
17
- import { parseArgs } from '../index';
18
-
19
- describe('AC-623-01: --files separates on any whitespace, not just spaces', () => {
20
- it('splits a newline-separated list (the CI shape)', () => {
21
- const opts = parseArgs(['--files', 'a.ts\nb.ts\nc.ts']);
22
- expect(opts.files).toEqual(['a.ts', 'b.ts', 'c.ts']);
23
- });
24
-
25
- it('splits a space-separated list', () => {
26
- const opts = parseArgs(['--files', 'a.ts b.ts']);
27
- expect(opts.files).toEqual(['a.ts', 'b.ts']);
28
- });
29
-
30
- it('splits a tab-separated list', () => {
31
- const opts = parseArgs(['--files', 'a.ts\tb.ts']);
32
- expect(opts.files).toEqual(['a.ts', 'b.ts']);
33
- });
34
-
35
- it('drops the blank entries a trailing separators leave behind', () => {
36
- const opts = parseArgs(['--files', 'a.ts\n\nb.ts\n']);
37
- expect(opts.files).toEqual(['a.ts', 'b.ts']);
38
- });
39
-
40
- it('keeps a single path intact', () => {
41
- const opts = parseArgs(['--files', 'src/one.ts']);
42
- expect(opts.files).toEqual(['src/one.ts']);
43
- });
44
- });
45
-
46
- describe('AC-623-02: a flag after --files is still parsed', () => {
47
- it('reads --format sarif that follows a multi-line --files value', () => {
48
- const opts = parseArgs(['--files', 'a.ts\nb.ts', '--format', 'sarif']);
49
- expect(opts.format).toBe('sarif');
50
- expect(opts.files).toEqual(['a.ts', 'b.ts']);
51
- });
52
-
53
- it('reads --format when it comes before --files', () => {
54
- const opts = parseArgs(['--format', 'sarif', '--files', 'a.ts\nb.ts']);
55
- expect(opts.format).toBe('sarif');
56
- });
57
- });
58
-
59
- describe('AC-623-03: positional paths still accumulate', () => {
60
- it('collects bare paths given without --files', () => {
61
- const opts = parseArgs(['a.ts', 'b.ts']);
62
- expect(opts.files).toEqual(['a.ts', 'b.ts']);
63
- });
64
-
65
- it('accepts --files alongside positional paths', () => {
66
- const opts = parseArgs(['--files', 'a.ts\nb.ts', 'c.ts']);
67
- expect(opts.files).toEqual(['a.ts', 'b.ts', 'c.ts']);
68
- });
69
- });
@@ -1,106 +0,0 @@
1
- /**
2
- * @test REQ-726
3
- * @intent 新增 `arch` 配置分组不得破坏既有用户配置。老项目的 .principlesrc 只写了
4
- * clean-code / solid 两个键,加载后 arch 必须取默认值而不是报错或变 undefined,
5
- * 否则升级即崩,用户不会去读变更日志。
6
- * @covers AC-COMPAT-01 AC-COMPAT-02
7
- */
8
- import { describe, it, expect, afterEach } from 'vitest';
9
- import { mkdtempSync, writeFileSync, rmSync } from 'fs';
10
- import { tmpdir } from 'os';
11
- import { join } from 'path';
12
- import { loadConfig } from '../config';
13
-
14
- /** Chosen to differ from every built-in default, so "it came from the file" is provable. */
15
- const CUSTOM_LONG_FUNCTION_THRESHOLD = 80;
16
- /** Likewise: no built-in large-file threshold is 900. */
17
- const CUSTOM_LARGE_FILE_THRESHOLD = 900;
18
-
19
- const dirs: string[] = [];
20
-
21
- /** Write a `.principlesrc` in a throwaway directory and return its path. */
22
- function configWith(contents: unknown): string {
23
- const dir = mkdtempSync(join(tmpdir(), 'xp-gate-arch-cfg-'));
24
- dirs.push(dir);
25
- const file = join(dir, '.principlesrc');
26
- try {
27
- writeFileSync(file, JSON.stringify(contents), 'utf-8');
28
- } catch (error) {
29
- throw new Error(`failed to write fixture .principlesrc: ${String(error)}`);
30
- }
31
- return file;
32
- }
33
-
34
- // Fixtures are built as named step-wise objects rather than deep inline literals:
35
- // the `deep-nesting` rule counts every brace, so a 4-level config literal nested
36
- // inside a call reads as 5 levels.
37
- const LONG_FUNCTION_OVERRIDE = { threshold: CUSTOM_LONG_FUNCTION_THRESHOLD };
38
- const LEGACY_ONLY_RULES = { 'clean-code': { 'long-function': LONG_FUNCTION_OVERRIDE } };
39
-
40
- const UTIL_SERVICE_OVERRIDE = { severity: 'info' };
41
- const PARTIAL_ARCH_RULES = { arch: { 'util-service': UTIL_SERVICE_OVERRIDE } };
42
-
43
- const LARGE_FILE_OVERRIDE = { threshold: CUSTOM_LARGE_FILE_THRESHOLD };
44
- const MISSPELT_GROUP_RULES = {
45
- archx: { whatever: { severity: 'error' } },
46
- 'clean-code': { 'large-file': LARGE_FILE_OVERRIDE },
47
- };
48
-
49
- /** A config that only touches a pre-existing group, as an old user's file would. */
50
- function legacyOnlyConfig(): string {
51
- return configWith({ rules: LEGACY_ONLY_RULES });
52
- }
53
-
54
- /** A config whose only arch entry is `util-service`. */
55
- function partialArchConfig(): string {
56
- return configWith({ rules: PARTIAL_ARCH_RULES });
57
- }
58
-
59
- /** A config with a misspelt group name plus one real clean-code override. */
60
- function typoGroupConfig(): string {
61
- return configWith({ rules: MISSPELT_GROUP_RULES });
62
- }
63
-
64
- afterEach(() => {
65
- while (dirs.length > 0) {
66
- const dir = dirs.pop();
67
- if (dir) rmSync(dir, { recursive: true, force: true });
68
- }
69
- });
70
-
71
- describe('AC-COMPAT-01 — 老配置(无 arch 键)照样工作', () => {
72
- it('只含 clean-code / solid 时,arch 分组取默认值且不报错', async () => {
73
- const config = await loadConfig(legacyOnlyConfig());
74
-
75
- // The two pre-existing groups keep behaving as before...
76
- expect(config.rules['clean-code']['long-function'].threshold)
77
- .toBe(CUSTOM_LONG_FUNCTION_THRESHOLD);
78
- expect(config.rules['solid'].srp).toBeDefined();
79
- // ...and the new group is fully populated from defaults.
80
- expect(config.rules.arch.controller.severity).toBe('error');
81
- expect(config.rules.arch['util-service'].severity).toBe('warning');
82
- });
83
-
84
- it('arch 分组存在但只写了一条时,其余仍取默认值', async () => {
85
- const config = await loadConfig(partialArchConfig());
86
-
87
- expect(config.rules.arch['util-service'].severity).toBe('info');
88
- // Siblings are NOT wiped by the partial block -- that fail-open shape is
89
- // what mergeGroup exists to prevent.
90
- expect(config.rules.arch.controller.severity).toBe('error');
91
- expect(config.rules.arch['dto-layering'].severity).toBe('error');
92
- });
93
- });
94
-
95
- describe('AC-COMPAT-02 — 未知分组不崩溃也不吞掉已知分组', () => {
96
- it('拼错的分组名(archx)不影响 clean-code / solid / arch 的加载', async () => {
97
- const config = await loadConfig(typoGroupConfig());
98
-
99
- // The known groups still load...
100
- expect(config.rules['clean-code']['large-file'].threshold)
101
- .toBe(CUSTOM_LARGE_FILE_THRESHOLD);
102
- expect(config.rules.arch.controller.severity).toBe('error');
103
- // ...and the typo does not become a real group.
104
- expect((config.rules as Record<string, unknown>).archx).toBeUndefined();
105
- });
106
- });
@@ -1,470 +0,0 @@
1
- /**
2
- * @test REQ-457
3
- * @intent `.principlesrc` must actually change what Gate 4 enforces. The rule
4
- * modules used to snapshot config at module load, so a project's
5
- * threshold was silently ignored and the checker enforced the built-in
6
- * default instead -- a fail-open gate.
7
- * @covers AC-457-01, AC-457-02, AC-457-03, AC-457-04, AC-457-05, AC-457-06, AC-457-07, AC-457-14, AC-457-15, AC-457-16, AC-457-10, AC-457-11, AC-457-13
8
- *
9
- * The pre-existing `config.test.ts` asserted only `expect(config).toBeDefined()`
10
- * for `loadConfig`, which is why the defect survived: the loader returned the
11
- * right object while nothing consumed it.
12
- *
13
- * These tests assert the *end-to-end* effect (an enforcement threshold changes),
14
- * not merely that a function returns a value.
15
- */
16
-
17
- import { mkdtempSync, rmSync, writeFileSync } from 'node:fs';
18
- import { spawnSync } from 'node:child_process';
19
- import { tmpdir } from 'node:os';
20
- import { join } from 'node:path';
21
- import { afterEach, beforeEach, describe, expect, it } from 'vitest';
22
- import {
23
- getActiveConfig,
24
- getDefaultConfig,
25
- getEffectiveConfigFor,
26
- loadConfig,
27
- resetActiveConfig,
28
- setActiveConfig,
29
- } from '../config';
30
- import { getAllRules } from '../index';
31
- import type { Adapter, Violation } from '../types';
32
-
33
- const tempDirs: string[] = [];
34
-
35
- /** Built-in default for large-file, per config.ts. */
36
- const DEFAULT_LARGE_FILE_THRESHOLD = 1150;
37
- /** A threshold far below the default, so a short stub violates it. */
38
- const TIGHT_THRESHOLD = 10;
39
- /** A threshold far above any stub, so nothing violates it. */
40
- const LOOSE_THRESHOLD = 100000;
41
- /** The line count our adapter stub reports. */
42
- const STUB_LINE_COUNT = 50;
43
- /** A small override for long-function, distinct from its default of 50. */
44
- const SHORT_THRESHOLD = 12;
45
- /** Built-in default for solid.srp's methodThreshold. */
46
- const DEFAULT_SRP_METHOD_THRESHOLD = 15;
47
-
48
- function makeTempDir(): string {
49
- const dir = mkdtempSync(join(tmpdir(), 'xpgate-457-'));
50
- tempDirs.push(dir);
51
- return dir;
52
- }
53
-
54
- /** Write a `.principlesrc` fixture into a temp dir and return its path. */
55
- function writeConfig(dir: string, contents: string, name = '.principlesrc'): string {
56
- const configPath = join(dir, name);
57
- try {
58
- writeFileSync(configPath, contents, 'utf8');
59
- } catch (error) {
60
- const detail = error instanceof Error ? error.message : String(error);
61
- throw new Error(`could not write fixture ${configPath}: ${detail}`);
62
- }
63
- return configPath;
64
- }
65
-
66
- /**
67
- * Run the real CLI in a child process and report both its exit status and its
68
- * parsed JSON. The exit code is part of this module's contract -- Gate 4 branches
69
- * on it -- so it can only be asserted through an actual process, not by calling
70
- * `main()` in-process.
71
- */
72
- function runChecker(args: string[], cwd = process.cwd()): { status: number; summary: Record<string, number> } {
73
- const result = spawnSync(
74
- process.execPath,
75
- [join(process.cwd(), 'node_modules', 'tsx', 'dist', 'cli.mjs'),
76
- join(process.cwd(), 'src', 'principles', 'index.ts'), ...args],
77
- { encoding: 'utf8', cwd, timeout: 120000 },
78
- );
79
- const stdout = result.stdout ?? '';
80
- let summary: Record<string, number> = {};
81
- try {
82
- summary = JSON.parse(stdout.slice(stdout.indexOf('{'))).summary;
83
- } catch {
84
- // A crash emits no parseable report; the caller asserts on `status`.
85
- }
86
- return { status: result.status ?? -1, summary };
87
- }
88
-
89
- /** A `.principlesrc` that sets one numeric threshold for one rule. */
90
- function thresholdConfig(ruleId: string, threshold: number): string {
91
- const rule = { [ruleId]: { threshold } };
92
- return JSON.stringify({ rules: { 'clean-code': rule } });
93
- }
94
-
95
- /** The same threshold, already merged into a config object (no disk involved). */
96
- function thresholdConfigObject(
97
- ruleId: keyof ReturnType<typeof getDefaultConfig>['rules']['clean-code'],
98
- threshold: number,
99
- ): ReturnType<typeof getDefaultConfig> {
100
- const config = getDefaultConfig();
101
- config.rules['clean-code'][ruleId].threshold = threshold;
102
- return config;
103
- }
104
-
105
- /** Run `body` with `[principles]` diagnostics captured instead of printed. */
106
- function capturePrinciplesWarnings(body: () => void): string[] {
107
- const captured: string[] = [];
108
- const original = process.stderr.write;
109
- process.stderr.write = ((chunk: unknown) => {
110
- const text = String(chunk);
111
- if (text.includes('[principles]')) captured.push(text.trim());
112
- return true;
113
- }) as typeof process.stderr.write;
114
- try {
115
- body();
116
- } finally {
117
- process.stderr.write = original;
118
- }
119
- return captured;
120
- }
121
-
122
- /** A `.principlesrc` that sets one array-valued key for one rule. */
123
- function arrayConfig(ruleId: string, key: string, values: number[]): string {
124
- const rule = { [ruleId]: { [key]: values } };
125
- return JSON.stringify({ rules: { 'clean-code': rule } });
126
- }
127
-
128
- /** Minimal adapter stub: reports a fixed line count so large-file is decidable. */
129
- function adapterReportingLines(totalLines: number): Adapter {
130
- return {
131
- detectLanguage: () => 'typescript',
132
- parseAST: () => ({}),
133
- extractFunctions: () => [],
134
- extractClasses: () => [],
135
- extractExports: () => [],
136
- countLines: () => totalLines,
137
- getDuplication: () => ({ percentage: 0, blocks: [] }), declaresRuleCoverage: true
138
- };
139
- }
140
-
141
- /** Run the real large-file rule against a stub reporting `lines` lines. */
142
- function checkLargeFile(lines: number): Violation[] {
143
- const rule = getAllRules().find(candidate => candidate.id === 'clean-code.large-file');
144
- if (!rule) throw new Error('clean-code.large-file rule is not registered');
145
- return rule.check('sample.ts', adapterReportingLines(lines));
146
- }
147
-
148
- afterEach(() => {
149
- resetActiveConfig();
150
- for (const dir of tempDirs.splice(0)) {
151
- try {
152
- rmSync(dir, { recursive: true, force: true });
153
- } catch {
154
- /* best effort */
155
- }
156
- }
157
- });
158
-
159
- beforeEach(() => {
160
- resetActiveConfig();
161
- });
162
-
163
- describe('#457 .principlesrc actually changes enforcement', () => {
164
- it('AC-457-01: getActiveConfig/setActiveConfig expose the effective config', () => {
165
- const custom = getDefaultConfig();
166
- custom.rules['clean-code']['large-file'].threshold = TIGHT_THRESHOLD;
167
- setActiveConfig(custom);
168
- expect(getActiveConfig().rules['clean-code']['large-file'].threshold).toBe(TIGHT_THRESHOLD);
169
- });
170
-
171
- it('AC-457-01: resetActiveConfig restores the built-in defaults', () => {
172
- const custom = getDefaultConfig();
173
- custom.rules['clean-code']['large-file'].threshold = TIGHT_THRESHOLD;
174
- setActiveConfig(custom);
175
- resetActiveConfig();
176
- expect(getActiveConfig().rules['clean-code']['large-file'].threshold).toBe(
177
- DEFAULT_LARGE_FILE_THRESHOLD
178
- );
179
- });
180
-
181
- it('AC-457-01: getDefaultConfig returns a fresh copy each call', () => {
182
- // Regression guard: hoisting the defaults to module constants made
183
- // getDefaultConfig() hand out SHARED objects, so one caller's mutation
184
- // corrupted the defaults for every later caller in the process.
185
- const first = getDefaultConfig();
186
- first.rules['clean-code']['large-file'].threshold = TIGHT_THRESHOLD;
187
- first.rules['clean-code']['magic-numbers'].exclude = [0];
188
-
189
- const second = getDefaultConfig();
190
- expect(second.rules['clean-code']['large-file'].threshold).toBe(
191
- DEFAULT_LARGE_FILE_THRESHOLD
192
- );
193
- expect(second.rules['clean-code']['magic-numbers'].exclude).toContain(1024);
194
- });
195
-
196
- it('AC-457-02: the large-file rule honours the ACTIVE threshold, not the default', () => {
197
- // This is the defect's core: the module captured the default at import
198
- // time, so a lower project threshold had no effect.
199
- const strict = getDefaultConfig();
200
- strict.rules['clean-code']['large-file'].threshold = TIGHT_THRESHOLD;
201
- setActiveConfig(strict);
202
-
203
- // Below the default (1150) but above the configured 10.
204
- const violations = checkLargeFile(STUB_LINE_COUNT);
205
- expect(violations.length).toBeGreaterThan(0);
206
- expect(violations[0].message).toContain(String(TIGHT_THRESHOLD));
207
- });
208
-
209
- it('AC-457-02: raising the threshold suppresses violations the default would report', () => {
210
- const relaxed = getDefaultConfig();
211
- relaxed.rules['clean-code']['large-file'].threshold = LOOSE_THRESHOLD;
212
- setActiveConfig(relaxed);
213
-
214
- expect(checkLargeFile(STUB_LINE_COUNT)).toHaveLength(0);
215
- });
216
-
217
- it('AC-457-04: `enabled: false` disables a rule (previously ignored everywhere)', () => {
218
- const disabled = getDefaultConfig();
219
- disabled.rules['clean-code']['large-file'].enabled = false;
220
- setActiveConfig(disabled);
221
-
222
- expect(checkLargeFile(STUB_LINE_COUNT)).toHaveLength(0);
223
- });
224
-
225
- it('AC-457-06: loadConfig reads a config from an explicit path', async () => {
226
- const configPath = writeConfig(makeTempDir(), thresholdConfig('large-file', 300));
227
-
228
- const config = await loadConfig(configPath);
229
- expect(config.rules['clean-code']['large-file'].threshold).toBe(300);
230
- // Unspecified fields keep their defaults (deep merge, not replacement).
231
- expect(config.rules['clean-code']['large-file'].severity).toBe('warning');
232
- expect(config.rules['clean-code']['long-function'].threshold).toBe(50);
233
- });
234
-
235
- it('AC-457-05: a partial override preserves the untouched rule group', async () => {
236
- // Regression guard: a shallow group-level spread would drop `solid`
237
- // entirely when the file only mentions `clean-code`.
238
- const raw = thresholdConfig('long-function', SHORT_THRESHOLD);
239
- const config = await loadConfig(writeConfig(makeTempDir(), raw));
240
-
241
- expect(config.rules['solid']['srp'].methodThreshold).toBe(DEFAULT_SRP_METHOD_THRESHOLD);
242
- expect(config.rules['solid']['dip'].enabled).toBe(true);
243
- });
244
-
245
- it('AC-457-10: a partial output block keeps the sibling output defaults', async () => {
246
- // `rules` was deep-merged but the other nested sections were not, so naming
247
- // one key under `output` discarded its siblings -- the same fail-open shape
248
- // #457 was raised to eliminate. Raised by the Delphi walkthrough (MC-02).
249
- const config = await loadConfig(
250
- writeConfig(makeTempDir(), JSON.stringify({ output: { format: 'json' } }), 'out.json'),
251
- );
252
-
253
- expect(config.output?.format).toBe('json');
254
- expect(config.output?.['show-score']).toBe(true);
255
- expect(config.output?.colorize).toBe(true);
256
- });
257
-
258
- it('AC-457-10: a partial performance block keeps the sibling defaults', async () => {
259
- const config = await loadConfig(
260
- writeConfig(makeTempDir(), JSON.stringify({ performance: { mode: 'all-files' } }), 'perf.json'),
261
- );
262
-
263
- expect(config.performance?.mode).toBe('all-files');
264
- expect(config.performance?.mediumProjectDefinition).toBeDefined();
265
- });
266
-
267
- it('AC-457-05: an array override replaces rather than concatenates', async () => {
268
- const raw = arrayConfig('magic-numbers', 'exclude', [0, 1]);
269
- const config = await loadConfig(writeConfig(makeTempDir(), raw));
270
-
271
- expect(config.rules['clean-code']['magic-numbers'].exclude).toEqual([0, 1]);
272
- });
273
-
274
- it('AC-457-07: a malformed config falls back to defaults without throwing', async () => {
275
- const config = await loadConfig(writeConfig(makeTempDir(), '{ this is not json'));
276
-
277
- expect(config.rules['clean-code']['large-file'].threshold).toBe(DEFAULT_LARGE_FILE_THRESHOLD);
278
- });
279
-
280
- it('AC-457-02: an absent auto-resolved config falls back to built-in defaults', () => {
281
- // No --config was given, so "this project has no .principlesrc" is a normal
282
- // state and must not fail. Run from a temp directory: the repo's own
283
- // .principlesrc would otherwise answer the question before the code does.
284
- const root = makeTempDir();
285
- const target = join(root, 'target.ts');
286
- writeFileSync(target, 'export const x = 1;\n', 'utf8');
287
-
288
- const clean = runChecker(['--files', target, '--format', 'json'], root);
289
-
290
- expect(clean.status).toBe(0);
291
- });
292
-
293
- it('AC-457-14: an explicitly requested config that cannot be read fails loudly', async () => {
294
- // Raised by the Delphi walkthrough (feasibility seat, FC-08). The caller
295
- // declared this file; silently enforcing built-in defaults instead is the
296
- // same fail-open shape #457 exists to remove, just reached from the other
297
- // direction -- a typo'd or deleted `.principlesrc` would keep the gate green.
298
- const missing = join(makeTempDir(), 'does-not-exist.json');
299
-
300
- await expect(loadConfig(missing)).rejects.toThrow(/config file not found/);
301
- });
302
-
303
- it('AC-457-14: the CLI reports that failure as a tool error (exit 2), not as findings', () => {
304
- // Exit 1 means "the checker ran and found ERROR-severity violations". A gate
305
- // that reads 1 with an empty report announces PASSED. Exit 2 is this repo's
306
- // runtime-error convention, which Gate 4 downgrades to SKIP -- loud, visible,
307
- // and never mistaken for a clean run.
308
- const missing = join(makeTempDir(), 'does-not-exist.json');
309
- const target = join(makeTempDir(), 'target.ts');
310
- writeFileSync(target, 'export const x = 1;\n', 'utf8');
311
-
312
- const failed = runChecker(['--files', target, '--format', 'json', '--config', missing]);
313
-
314
- expect(failed.status).toBe(2);
315
- });
316
-
317
- it('AC-457-07: a type-mismatched value keeps the default instead of poisoning it', async () => {
318
- const bad = thresholdConfig('large-file', 'not-a-number' as unknown as number);
319
- const config = await loadConfig(writeConfig(makeTempDir(), bad));
320
-
321
- expect(config.rules['clean-code']['large-file'].threshold).toBe(DEFAULT_LARGE_FILE_THRESHOLD);
322
- });
323
-
324
- it('AC-457-04: config read from disk is what the rule then enforces', async () => {
325
- // The end-to-end contract: load -> activate -> enforce.
326
- const configPath = writeConfig(makeTempDir(), thresholdConfig('large-file', 5));
327
- setActiveConfig(await loadConfig(configPath));
328
-
329
- expect(checkLargeFile(STUB_LINE_COUNT).length).toBeGreaterThan(0);
330
- });
331
-
332
- // AC-457-08/09: the exit code has to separate "violations found" from "the
333
- // checker crashed". Gate 4 decides by testing the exit status (`if run_tsx ...`),
334
- // so a crash and an error-severity finding that share exit 1 are indistinguishable.
335
- // Fixing #457 alone moved the hole rather than closing it: warnings no longer look
336
- // like crashes, but ERROR-severity violations now do -- and the gate SKIPs,
337
- // releasing exactly the most serious findings. Found by the Delphi walkthrough.
338
- it('AC-457-08: exits 1 for an ERROR-severity violation and 0 without one', () => {
339
- const root = makeTempDir();
340
- const target = join(root, 'target.ts');
341
- writeFileSync(target, 'export const x = 1;\n', 'utf8');
342
- const strict = writeConfig(root, '{"rules":{"clean-code":{"large-file":{"enabled":true,"threshold":1,"severity":"error"}}}}');
343
-
344
- const blocking = runChecker(['--files', target, '--format', 'json', '--config', strict]);
345
- expect(blocking.summary.errorCount).toBeGreaterThan(0);
346
- expect(blocking.status).toBe(1);
347
-
348
- const loose = writeConfig(root, '{"rules":{"clean-code":{"large-file":{"enabled":true,"threshold":100000}}}}', 'loose.json');
349
- const clean = runChecker(['--files', target, '--format', 'json', '--config', loose]);
350
- expect(clean.status).toBe(0);
351
- });
352
-
353
- it('AC-457-09: a checker crash exits 2, not 1, so gates can tell it from violations', () => {
354
- // Exit 2 is this repo's existing convention for "tool ran into a runtime
355
- // error" (see src/gates/gate-8.ts and gate-9.ts, which SKIP on exit >= 2 and
356
- // treat 1 as a real finding).
357
- const missing = join(makeTempDir(), 'never-written.ts');
358
-
359
- const crashed = runChecker(['--files', missing, '--format', 'json']);
360
-
361
- expect(crashed.status).toBe(2);
362
- });
363
-
364
- it('AC-457-09: a usage error also exits 2, never the findings code', () => {
365
- // Raised by the Delphi walkthrough (architecture seat, MC-01). Returning 1
366
- // here means "I found ERROR-severity violations" under the contract this
367
- // change introduces. Gate 4 branches on >=2 for the crash path, so exit 1 plus
368
- // an empty report reads as "checked everything, found nothing": the gate would
369
- // announce PASSED having examined no files at all.
370
- const misused = runChecker(['--format', 'json']);
371
-
372
- expect(misused.status).toBe(2);
373
- });
374
-
375
- // Severity override fixture. Hoisted so both cases below read as a loop over
376
- // values rather than a loop over nested literals.
377
- const severityConfig = (severity: string) => JSON.stringify({
378
- rules: { 'clean-code': { 'large-file': { enabled: true, threshold: 1, severity } } },
379
- });
380
-
381
- it('AC-457-11: a severity outside the vocabulary is rejected, not silently obeyed', async () => {
382
- // Raised by the Delphi walkthrough (architecture seat, MJ-01). `severity` was
383
- // validated only as "non-empty string", but both summary.errorCount and Gate 4's
384
- // grep match the exact lowercase literal `error`. Measured with severity "Error":
385
- // the rule still runs, still reports the violation, yet errorCount is 0, exit is
386
- // 0, and the gate passes -- a typo that silently un-blocks a rule with no warning
387
- // anywhere. Same fail-open shape #457 exists to remove.
388
- const dir = makeTempDir();
389
-
390
- for (const bad of ['Error', 'ERROR', 'errorX', 'fatal']) {
391
- const config = await loadConfig(writeConfig(dir, severityConfig(bad)));
392
- expect(config.rules['clean-code']['large-file'].severity).toBe('warning');
393
- }
394
- });
395
-
396
- it('AC-457-11: the three documented severities are all accepted', async () => {
397
- const dir = makeTempDir();
398
- for (const good of ['error', 'warning', 'info']) {
399
- const config = await loadConfig(writeConfig(dir, severityConfig(good)));
400
- expect(config.rules['clean-code']['large-file'].severity).toBe(good);
401
- }
402
- });
403
-
404
- it('AC-457-13: every rule id has exactly one dot, as config lookup requires', () => {
405
- // isRuleEnabled splits on the FIRST dot to get group and name. A future id like
406
- // `clean-code.sub.rule` would resolve to group "clean-code", name "sub.rule",
407
- // find no config entry, and default to enabled with built-in thresholds --
408
- // silently ignoring whatever the project configured. The invariant held by
409
- // inspection until this test said so (Delphi walkthrough FC-04).
410
- const ids = getAllRules().map((rule) => rule.id);
411
-
412
- expect(ids.length).toBeGreaterThan(0);
413
- for (const id of ids) {
414
- expect(id.split('.')).toHaveLength(2);
415
- }
416
- });
417
-
418
- it('AC-457-13: every rule id resolves to a real group in the config', () => {
419
- const groups = Object.keys(getDefaultConfig().rules);
420
- for (const rule of getAllRules()) {
421
- expect(groups).toContain(rule.id.slice(0, rule.id.indexOf('.')));
422
- }
423
- });
424
-
425
- it('AC-457-16: getEffectiveConfigFor reports the config a rule actually enforces', () => {
426
- // Promised by the R2 design review (walkthrough MAJ-03 / FC-05) and never
427
- // delivered: `Rule.threshold` on the rule object is a deprecated snapshot, so
428
- // a consumer that reads it sees a number that may differ from what `check()`
429
- // compared against. This is the one accessor that cannot drift.
430
- setActiveConfig(thresholdConfigObject('large-file', TIGHT_THRESHOLD));
431
-
432
- expect(getEffectiveConfigFor('clean-code.large-file').threshold).toBe(TIGHT_THRESHOLD);
433
- expect(getDefaultConfig().rules['clean-code']['large-file'].threshold).toBe(
434
- DEFAULT_LARGE_FILE_THRESHOLD
435
- );
436
- });
437
-
438
- it('AC-457-16: an unknown or malformed rule id is refused, not answered with defaults', () => {
439
- // Silently handing back built-in defaults would recreate the fail-open shape
440
- // for the *reporting* path: a caller would believe it read the effective
441
- // threshold for a rule that does not exist.
442
- expect(() => getEffectiveConfigFor('clean-code.not-a-rule')).toThrow(/no rule/);
443
- expect(() => getEffectiveConfigFor('large-file')).toThrow(/group.name/);
444
- });
445
-
446
- it('AC-457-15: replacing the active config without resetting it is reported', () => {
447
- // The concurrency contract used to live only in a JSDoc comment (walkthrough
448
- // FC-02). A caller that evaluates two projects in one process would silently
449
- // enforce whichever config happened to be installed last.
450
- const warnings = capturePrinciplesWarnings(() => {
451
- setActiveConfig(thresholdConfigObject('large-file', TIGHT_THRESHOLD));
452
- setActiveConfig(thresholdConfigObject('large-file', LOOSE_THRESHOLD));
453
- });
454
-
455
- expect(warnings.join('\n')).toMatch(/replaced without reset/);
456
- });
457
-
458
- it('AC-457-15: the documented single-set lifecycle stays quiet', () => {
459
- // The guardrail must not turn the normal CLI path (load -> set once -> run)
460
- // into warning noise, otherwise Gate 4's stderr becomes unreadable.
461
- const warnings = capturePrinciplesWarnings(() => {
462
- resetActiveConfig();
463
- setActiveConfig(thresholdConfigObject('large-file', TIGHT_THRESHOLD));
464
- resetActiveConfig();
465
- setActiveConfig(thresholdConfigObject('large-file', LOOSE_THRESHOLD));
466
- });
467
-
468
- expect(warnings).toEqual([]);
469
- });
470
- });