@boyingliu01/xp-gate 0.36.1 → 0.37.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (123) hide show
  1. package/adapters/cpp.sh +78 -10
  2. package/adapters/csharp.sh +58 -3
  3. package/adapters/gate-3.sh +15 -5
  4. package/adapters/gate-8.sh +131 -9
  5. package/adapters/typescript.sh +32 -8
  6. package/build-integrity/__tests__/import-resolver.test.ts +257 -0
  7. package/build-integrity/__tests__/quote-masker.test.ts +177 -0
  8. package/build-integrity/gate-10.ts +127 -9
  9. package/build-integrity/quote-masker.ts +266 -0
  10. package/gate-10.sh +66 -0
  11. package/gate-12-file-hygiene.sh +15 -7
  12. package/gate-13-compiler-strictness.sh +81 -1
  13. package/gate-3.sh +15 -5
  14. package/gate-6-layers.sh +375 -0
  15. package/gate-8.sh +131 -9
  16. package/hooks/gate-10.sh +66 -0
  17. package/hooks/gate-12-file-hygiene.sh +15 -7
  18. package/hooks/gate-13-compiler-strictness.sh +81 -1
  19. package/hooks/gate-3.sh +15 -5
  20. package/hooks/gate-6-layers.sh +375 -0
  21. package/hooks/gate-8.sh +131 -9
  22. package/hooks/gate-registry.sh +2 -2
  23. package/hooks/hook-module-resolution.sh +1 -1
  24. package/hooks/lib/assertion-quality.sh +8 -2
  25. package/hooks/lib/ccn-ratchet.sh +10 -0
  26. package/hooks/lib/layer-baseline.cjs +88 -0
  27. package/hooks/lib/typecheck.sh +28 -5
  28. package/hooks/pre-commit +376 -53
  29. package/hooks/pre-push +46 -13
  30. package/lib/__tests__/agent-runtime-journal.test.js +1 -1
  31. package/lib/__tests__/arch.test.js +9 -0
  32. package/lib/__tests__/audit-cli-contract.test.ts +1 -1
  33. package/lib/__tests__/check-alignment-reasons.test.mjs +11 -1
  34. package/lib/__tests__/check-all-skip-accounting.test.js +1 -1
  35. package/lib/__tests__/detect-deps-gate-identity.test.js +135 -0
  36. package/lib/__tests__/detect-deps.test.js +2 -1
  37. package/lib/__tests__/doctor-469-hook-env.test.js +7 -1
  38. package/lib/__tests__/doctor-arch-tools.test.js +169 -0
  39. package/lib/__tests__/doctor-delphi.test.js +1 -1
  40. package/lib/__tests__/doctor-drift-round2.test.js +4 -1
  41. package/lib/__tests__/doctor-executed-surface.test.js +45 -24
  42. package/lib/__tests__/doctor-module-drift.test.js +13 -7
  43. package/lib/__tests__/doctor-module-resolution-parity.test.js +74 -2
  44. package/lib/__tests__/doctor-tui-skill-freshness.test.js +21 -6
  45. package/lib/__tests__/doctor.test.js +17 -0
  46. package/lib/__tests__/gate-runner-tsx-invocation.test.js +149 -0
  47. package/lib/__tests__/gate-runner.test.js +23 -7
  48. package/lib/__tests__/init-gitignore.test.js +204 -0
  49. package/lib/__tests__/init.test.js +24 -3
  50. package/lib/__tests__/language-tools-build-file-install.test.js +82 -0
  51. package/lib/__tests__/language-tools-detect.test.js +61 -0
  52. package/lib/__tests__/mirror-sync.test.js +2 -0
  53. package/lib/__tests__/phase-transition.test.js +19 -1
  54. package/lib/__tests__/sprint-status-rework.test.js +32 -12
  55. package/lib/__tests__/test-alignment-range-guard.test.ts +82 -0
  56. package/lib/__tests__/test-alignment.test.ts +13 -3
  57. package/lib/__tests__/update-skill.test.js +2 -2
  58. package/lib/detect-deps.js +7 -1
  59. package/lib/doctor.js +81 -17
  60. package/lib/gate-runner.js +101 -7
  61. package/lib/hook-module-resolution.js +18 -6
  62. package/lib/init.js +136 -1
  63. package/lib/language-tools.js +217 -1
  64. package/lib/layer-baseline.cjs +88 -0
  65. package/lib/mattpocock-license-verdict.json +1 -1
  66. package/lib/principles.js +21 -6
  67. package/lib/test-alignment.ts +452 -55
  68. package/mock-policy/AGENTS.md +1 -1
  69. package/mutation/AGENTS.md +1 -1
  70. package/package.json +2 -1
  71. package/plugins/claude-code/.claude-plugin/plugin.json +1 -1
  72. package/plugins/claude-code/skills/delphi-review/.delphi-config.json.example +34 -24
  73. package/plugins/claude-code/skills/delphi-review/AGENTS.md +1 -1
  74. package/plugins/claude-code/skills/delphi-review/INSTALL.md +29 -1
  75. package/plugins/claude-code/skills/sprint-flow/AGENTS.md +1 -1
  76. package/plugins/claude-code/skills/test-specification-alignment/AGENTS.md +1 -1
  77. package/plugins/dsh/package.json +1 -1
  78. package/plugins/dsh/skills/delphi-review/.delphi-config.json.example +34 -24
  79. package/plugins/dsh/skills/delphi-review/AGENTS.md +1 -1
  80. package/plugins/dsh/skills/delphi-review/INSTALL.md +29 -1
  81. package/plugins/dsh/skills/sprint-flow/AGENTS.md +1 -1
  82. package/plugins/dsh/skills/test-specification-alignment/AGENTS.md +1 -1
  83. package/plugins/dsh/src/client.test.ts +1 -1
  84. package/plugins/dsh/src/command.test.ts +1 -1
  85. package/plugins/dsh/src/contract.test.ts +1 -1
  86. package/plugins/dsh/src/credentials.test.ts +1 -1
  87. package/plugins/opencode/package.json +1 -1
  88. package/plugins/opencode/skills/delphi-review/.delphi-config.json.example +34 -24
  89. package/plugins/opencode/skills/delphi-review/AGENTS.md +1 -1
  90. package/plugins/opencode/skills/delphi-review/INSTALL.md +29 -1
  91. package/plugins/opencode/skills/sprint-flow/AGENTS.md +1 -1
  92. package/plugins/opencode/skills/test-specification-alignment/AGENTS.md +1 -1
  93. package/plugins/qoder/plugin.json +1 -1
  94. package/plugins/qoder/skills/delphi-review/.delphi-config.json.example +34 -24
  95. package/plugins/qoder/skills/delphi-review/AGENTS.md +1 -1
  96. package/plugins/qoder/skills/delphi-review/INSTALL.md +29 -1
  97. package/plugins/qoder/skills/sprint-flow/AGENTS.md +1 -1
  98. package/plugins/qoder/skills/test-specification-alignment/AGENTS.md +1 -1
  99. package/principles/AGENTS.md +1 -1
  100. package/principles/__tests__/config-arch-group.test.ts +106 -0
  101. package/principles/__tests__/config-enforcement.test.ts +1 -1
  102. package/principles/adapters/control-nesting.ts +572 -0
  103. package/principles/adapters/csharp.ts +73 -42
  104. package/principles/adapters/java.ts +9 -5
  105. package/principles/adapters/typescript.ts +138 -176
  106. package/principles/config.ts +37 -2
  107. package/principles/index.ts +57 -4
  108. package/principles/reporter.ts +99 -65
  109. package/principles/rules/arch/__tests__/dependency.test.ts +180 -0
  110. package/principles/rules/arch/__tests__/naming.test.ts +133 -0
  111. package/principles/rules/arch/__tests__/shared.test.ts +113 -0
  112. package/principles/rules/arch/dependency.ts +264 -0
  113. package/principles/rules/arch/naming.ts +188 -0
  114. package/principles/rules/arch/shared.ts +169 -0
  115. package/principles/rules/exports.ts +26 -0
  116. package/principles/rules/index.ts +11 -18
  117. package/scripts/__tests__/sync-package-content.test.js +23 -1
  118. package/scripts/sync-package-content.js +8 -2
  119. package/skills/delphi-review/.delphi-config.json.example +34 -24
  120. package/skills/delphi-review/AGENTS.md +1 -1
  121. package/skills/delphi-review/INSTALL.md +29 -1
  122. package/skills/sprint-flow/AGENTS.md +1 -1
  123. package/skills/test-specification-alignment/AGENTS.md +1 -1
@@ -3,6 +3,7 @@ import { formatConsole, formatJSON, formatSARIF } from './reporter';
3
3
  import { loadConfig, setActiveConfig } from './config';
4
4
  import { getAllPrincipleRules } from './rules';
5
5
  import { isDirectExecution } from './direct-execution.js';
6
+ import { statSync } from 'node:fs';
6
7
 
7
8
  interface CLIOptions {
8
9
  files: string[];
@@ -149,13 +150,65 @@ function exitStatusFor(result: { errors: string[]; summary: { errorCount: number
149
150
  return result.summary.errorCount > 0 ? 1 : 0;
150
151
  }
151
152
 
152
- export async function main(args: string[]): Promise<number> {
153
- const options = parseArgs(args);
153
+ /**
154
+ * Reject a DIRECTORY passed where a file is expected.
155
+ *
156
+ * `--files src/utils` (or any bare directory path) reached `analyze`, which
157
+ * could not read it, filed NO error, and reported `Files checked: 0` with
158
+ * "✓ No violations found" and exit 0. That is the same false-clean shape #623
159
+ * fixed for unreadable files, except an unreadable file at least produced
160
+ * "Analysis incomplete"; a directory produced silence because reading it fails
161
+ * differently from opening a file.
162
+ *
163
+ * Returns the offending paths so the caller can name them. An operator who
164
+ * points the checker at a directory needs to be told to expand it or use the
165
+ * gate wrapper, not handed a pass.
166
+ */
167
+ function findDirectories(paths: readonly string[]): string[] {
168
+ const dirs: string[] = [];
169
+ for (const p of paths) {
170
+ try {
171
+ if (statSync(p).isDirectory()) dirs.push(p);
172
+ } catch {
173
+ // Missing paths are analyze()'s job to report, not this check's.
174
+ }
175
+ }
176
+ return dirs;
177
+ }
154
178
 
155
- if (options.files.length === 0) {
179
+ /**
180
+ * Reject a usage the checker cannot honestly answer, reporting why.
181
+ *
182
+ * Two cases, one decision: nothing was analysed, so "no violations found" would
183
+ * be a claim about files that were never read. An empty argument list is a
184
+ * usage error; so is a directory handed in where a file was expected — the
185
+ * latter previously reached `analyze`, which could not read it, filed NO error,
186
+ * and reported `Files checked: 0` with "✓ No violations found" and exit 0. That
187
+ * is the same false-clean shape #623 fixed for unreadable files, except a
188
+ * directory produced silence because reading it fails differently from opening
189
+ * a file.
190
+ *
191
+ * Returns true when it has reported and the caller must stop.
192
+ */
193
+ function refuseUnanalysableInput(files: readonly string[]): boolean {
194
+ if (files.length === 0) {
156
195
  usageMessage();
157
- return USAGE_EXIT;
196
+ return true;
158
197
  }
198
+ const directories = findDirectories(files);
199
+ if (directories.length === 0) return false;
200
+ console.error(
201
+ `Cannot analyse a directory: ${directories.length} path(s) are directories, not files`,
202
+ );
203
+ for (const dir of directories) console.error(` ${dir}`);
204
+ console.error('Pass individual files, or run the gate wrapper: xp-gate check 4 <dir>');
205
+ return true;
206
+ }
207
+
208
+ export async function main(args: string[]): Promise<number> {
209
+ const options = parseArgs(args);
210
+
211
+ if (refuseUnanalysableInput(options.files)) return USAGE_EXIT;
159
212
 
160
213
  // Install the loaded config so rules read the PROJECT's thresholds. The
161
214
  // previous `await loadConfig();` discarded the result, so `.principlesrc` was
@@ -1,60 +1,60 @@
1
- import { AnalysisResult, Violation } from './analyzer';
1
+ import { AnalysisResult, AnalysisSummary, Violation } from './analyzer';
2
2
 
3
- export function formatSARIF(result: AnalysisResult): string {
3
+ /** Width of the horizontal rule that separates file blocks in console output. */
4
+ const CONSOLE_RULE_WIDTH = 40;
5
+
6
+ /** SARIF severity for a violation. SARIF calls `info` a "note". */
7
+ function toSarifLevel(severity: Violation['severity']): string {
8
+ if (severity === 'error') return 'error';
9
+ if (severity === 'warning') return 'warning';
10
+ return 'note';
11
+ }
12
+
13
+ /** Map one violation to its SARIF result entry. */
14
+ function toSarifResult(v: Violation): Record<string, unknown> {
15
+ const region = { startLine: v.line, startColumn: v.column || 1 };
16
+ const physicalLocation = { artifactLocation: { uri: v.file }, region };
17
+ return {
18
+ ruleId: v.ruleId,
19
+ level: toSarifLevel(v.severity),
20
+ message: { text: v.message },
21
+ locations: [{ physicalLocation }],
22
+ };
23
+ }
24
+
25
+ /** The `runs[0]` object: tool driver metadata plus every result. */
26
+ function buildSarifRun(result: AnalysisResult): Record<string, unknown> {
4
27
  const ruleDescriptors = Object.keys(result.ruleResults).map(ruleId => ({
5
28
  id: ruleId,
6
- shortDescription: {
7
- text: getRuleDescription(ruleId)
8
- },
9
- defaultConfiguration: {
10
- level: getRuleLevel(ruleId)
11
- }
29
+ shortDescription: { text: getRuleDescription(ruleId) },
30
+ defaultConfiguration: { level: getRuleLevel(ruleId) },
12
31
  }));
13
-
14
- const sarifResults = result.violations.map(v => ({
15
- ruleId: v.ruleId,
16
- level: v.severity === 'error' ? 'error' : v.severity === 'warning' ? 'warning' : 'note',
17
- message: {
18
- text: v.message
32
+
33
+ return {
34
+ tool: {
35
+ driver: {
36
+ name: 'Principles Checker',
37
+ version: '1.0.0',
38
+ informationUri: 'https://github.com/boyingliu01/xp-gate',
39
+ rules: ruleDescriptors,
40
+ },
19
41
  },
20
- locations: [
21
- {
22
- physicalLocation: {
23
- artifactLocation: {
24
- uri: v.file
25
- },
26
- region: {
27
- startLine: v.line,
28
- startColumn: v.column || 1
29
- }
30
- }
31
- }
32
- ]
33
- }));
34
-
42
+ results: result.violations.map(toSarifResult),
43
+ properties: {
44
+ filesChecked: result.summary.filesChecked,
45
+ rulesRun: result.summary.rulesRun,
46
+ executionTimeMs: result.executionTimeMs,
47
+ },
48
+ };
49
+ }
50
+
51
+ export function formatSARIF(result: AnalysisResult): string {
35
52
  const sarif = {
36
53
  $schema: 'https://raw.githubusercontent.com/oasis-tcs/sarif-spec/master/Schemata/sarif-schema-2.1.0.json',
37
54
  version: '2.1.0',
38
- runs: [
39
- {
40
- tool: {
41
- driver: {
42
- name: 'Principles Checker',
43
- version: '1.0.0',
44
- informationUri: 'https://github.com/boyingliu01/xp-gate',
45
- rules: ruleDescriptors
46
- }
47
- },
48
- results: sarifResults,
49
- properties: {
50
- filesChecked: result.summary.filesChecked,
51
- rulesRun: result.summary.rulesRun,
52
- executionTimeMs: result.executionTimeMs
53
- }
54
- }
55
- ]
55
+ runs: [buildSarifRun(result)],
56
56
  };
57
-
57
+
58
58
  return JSON.stringify(sarif, null, 2);
59
59
  }
60
60
 
@@ -73,7 +73,13 @@ function getRuleDescription(ruleId: string): string {
73
73
  'solid.ocp': 'Open/Closed Principle violation',
74
74
  'solid.lsp': 'Liskov Substitution Principle violation',
75
75
  'solid.isp': 'Interface Segregation Principle violation',
76
- 'solid.dip': 'Dependency Inversion Principle violation'
76
+ 'solid.dip': 'Dependency Inversion Principle violation',
77
+ 'arch.controller': 'Class in interfaces/rest must be named *Controller',
78
+ 'arch.service': 'Class in application/service must be named *Service or *ServiceImpl',
79
+ 'arch.repository': 'Class in infrastructure must be named *Mapper, *DAO or *Repository',
80
+ 'arch.dto-layering': 'DTO must not depend on a service or repository',
81
+ 'arch.domain-event': 'Domain event must not depend on the infrastructure layer',
82
+ 'arch.util-service': 'Utility depends on an application service'
77
83
  };
78
84
 
79
85
  return descriptions[ruleId] || ruleId;
@@ -113,7 +119,7 @@ function formatViolationLines(violation: Violation): string[] {
113
119
  function formatFileViolations(lines: string[], filesMap: Record<string, Violation[]>): void {
114
120
  for (const [file, violations] of Object.entries(filesMap)) {
115
121
  lines.push(`\n📁 ${file}`);
116
- lines.push('─'.repeat(40));
122
+ lines.push('─'.repeat(CONSOLE_RULE_WIDTH));
117
123
  for (const v of violations) {
118
124
  lines.push(...formatViolationLines(v));
119
125
  }
@@ -147,7 +153,7 @@ export function formatConsole(result: AnalysisResult): string {
147
153
  formatFileViolations(lines, filesMap);
148
154
 
149
155
  lines.push('');
150
- lines.push('─'.repeat(40));
156
+ lines.push('─'.repeat(CONSOLE_RULE_WIDTH));
151
157
  lines.push(formatSummary(result));
152
158
  lines.push(`Execution time: ${result.executionTimeMs}ms`);
153
159
 
@@ -169,20 +175,48 @@ export function formatJSON(result: AnalysisResult): string {
169
175
  return JSON.stringify(output, null, 2);
170
176
  }
171
177
 
178
+ /**
179
+ * A summary field read defensively, with every substitution recorded.
180
+ *
181
+ * `formatSummary` is exported, so it cannot assume its caller honoured the
182
+ * AnalysisResult type: a missing summary used to throw, and a partial one
183
+ * computed `undefined + 0 = NaN` -- where `NaN === 0` is false, so every commit
184
+ * reported FAIL forever. Zeroing alone is not enough either; it would turn a
185
+ * corrupted summary into "nothing to report", so each substitution is named.
186
+ */
187
+ function readCounts(summary: AnalysisSummary | undefined, damaged: string[]): number[] {
188
+ const fields: Array<keyof AnalysisSummary> = [
189
+ 'totalViolations', 'errorCount', 'warningCount', 'infoCount', 'filesChecked', 'rulesRun',
190
+ ];
191
+ return fields.map((field) => {
192
+ const value = summary?.[field];
193
+ if (typeof value === 'number' && Number.isFinite(value)) return value;
194
+ damaged.push(`${field}=${String(value)}`);
195
+ return 0;
196
+ });
197
+ }
198
+
172
199
  export function formatSummary(result: AnalysisResult): string {
173
- const status = result.violations.length === 0 ? 'PASS' : 'FAIL';
174
- const statusIcon = result.violations.length === 0 ? '✓' : '✗';
175
-
176
- const lines: string[] = [];
177
- lines.push(`${statusIcon} ${status}`);
178
- lines.push('');
179
- lines.push(`${result.summary.totalViolations} violations total`);
180
- lines.push(` ${result.summary.errorCount} errors`);
181
- lines.push(` ${result.summary.warningCount} warnings`);
182
- lines.push(` ${result.summary.infoCount} info`);
183
- lines.push('');
184
- lines.push(`${result.summary.filesChecked} files checked`);
185
- lines.push(`${result.summary.rulesRun} rules run`);
186
-
200
+ // `info` is "log only" (AGENTS.md). Counting it as a failure turned every
201
+ // rule's way of saying "I could not judge this file" into a blocked commit --
202
+ // the arch layout diagnostic surfaced exactly that. Only error and warning
203
+ // are blocking severities, so PASS/FAIL reads from those two alone.
204
+ const damaged: string[] = [];
205
+ const [total, errors, warnings, info, files, rules] = readCounts(result.summary, damaged);
206
+ const pass = errors + warnings === 0;
207
+ const lines = [
208
+ pass ? 'PASS' : 'FAIL',
209
+ '',
210
+ `${total} violations total`,
211
+ ` ${errors} errors`,
212
+ ` ${warnings} warnings`,
213
+ ` ${info} info`,
214
+ '',
215
+ `${files} files checked`,
216
+ `${rules} rules run`,
217
+ ];
218
+ if (damaged.length > 0) {
219
+ lines.push('', `! malformed summary: ${damaged.join(', ')} (read as 0; the counts above cannot be trusted)`);
220
+ }
187
221
  return lines.join('\n');
188
222
  }
@@ -0,0 +1,180 @@
1
+ /**
2
+ * @test REQ-728
3
+ * @intent Java 依赖方向规则 R08/R15/W01。三条规则分别用类名、包路径、文件名判定,
4
+ * 不是不一致而是各自表达的东西不同(见 dependency.ts 头注释)。
5
+ * @covers AC-728-01 AC-728-02 AC-728-03 AC-728-04 AC-728-05 AC-728-06 AC-728-07
6
+ * AC-728-08 AC-728-09 AC-728-10 AC-728-11 AC-728-12 AC-728-13 AC-728-14
7
+ */
8
+ import { describe, it, expect } from 'vitest';
9
+ import {
10
+ dtoLayeringRule,
11
+ domainEventRule,
12
+ utilServiceRule,
13
+ } from '../dependency';
14
+
15
+ /**
16
+ * Adapter stub. `imports` is a GETTER on the real adapter, so this mirrors that
17
+ * shape rather than exposing a plain array -- a rule that reads `.imports()`
18
+ * by mistake must fail here, not in production.
19
+ */
20
+ function adapter(imports: string[] = [], classes: string[] = []) {
21
+ return {
22
+ extractClasses: () => classes.map((name) => ({ name, line: 1 })),
23
+ get imports() {
24
+ return imports.map((name) => ({ name, line: 1, used: false, type: 'import' }));
25
+ },
26
+ };
27
+ }
28
+
29
+ const DTO_FILE = 'src/main/java/com/acme/interfaces/dto/UserDTO.java';
30
+
31
+ describe('R08 — DTO/VO 不得依赖 Service 或 Repository', () => {
32
+ it('AC-728-01: UserDTO import UserService -> 违规', () => {
33
+ const v = dtoLayeringRule.check(DTO_FILE, adapter(['com.acme.application.service.UserService']) as never);
34
+ expect(v).toHaveLength(1);
35
+ expect(v[0].ruleId).toBe('arch.dto-layering');
36
+ });
37
+
38
+ it('AC-728-02: OrderVO import OrderRepository -> 违规', () => {
39
+ const v = dtoLayeringRule.check(
40
+ 'src/main/java/com/acme/interfaces/vo/OrderVO.java',
41
+ adapter(['com.acme.infrastructure.repository.OrderRepository']) as never,
42
+ );
43
+ expect(v).toHaveLength(1);
44
+ });
45
+
46
+ it('AC-728-03: UserDTO 只 import javax.validation 注解 -> 通过', () => {
47
+ const v = dtoLayeringRule.check(
48
+ DTO_FILE,
49
+ adapter(['javax.validation.constraints.NotNull', 'java.util.List']) as never,
50
+ );
51
+ expect(v).toEqual([]);
52
+ });
53
+
54
+ // The exclusion list is the whole reason the suffix heuristic survives on a
55
+ // real codebase: `OrderServiceConstants` matches `*Service` but is not one.
56
+ it('AC-728-09: UserDTO import OrderServiceConstants -> 不报(排除后缀优先于命中)', () => {
57
+ const v = dtoLayeringRule.check(
58
+ DTO_FILE,
59
+ adapter(['com.acme.application.service.OrderServiceConstants']) as never,
60
+ );
61
+ expect(v).toEqual([]);
62
+ });
63
+
64
+ // A wildcard import carries no class name at all -- the Java adapter's regex
65
+ // does not even capture it. Documented in the design (§4.3) and pinned here so
66
+ // nobody "fixes" the rule into guessing a name from the package.
67
+ it('AC-728-14: DTO 中的通配 import 不参与 R08 判定', () => {
68
+ const v = dtoLayeringRule.check(DTO_FILE, adapter(['com.acme.service']) as never);
69
+ expect(v).toEqual([]);
70
+ });
71
+ });
72
+
73
+ describe('R15 — domain/event 不得依赖 infrastructure', () => {
74
+ const EVENT_FILE = 'src/main/java/com/acme/domain/event/OrderCompletedEvent.java';
75
+
76
+ it('AC-728-04: OrderCompletedEvent import infrastructure/kafka/KafkaClient -> 违规', () => {
77
+ const v = domainEventRule.check(
78
+ EVENT_FILE,
79
+ adapter(['com.acme.infrastructure.kafka.KafkaClient']) as never,
80
+ );
81
+ expect(v).toHaveLength(1);
82
+ expect(v[0].ruleId).toBe('arch.domain-event');
83
+ });
84
+
85
+ it('AC-728-05: domain/event import domain/model -> 通过', () => {
86
+ const v = domainEventRule.check(
87
+ EVENT_FILE,
88
+ adapter(['com.acme.domain.model.Order']) as never,
89
+ );
90
+ expect(v).toEqual([]);
91
+ });
92
+
93
+ // Wildcard imports never reach ANY rule: the Java adapter's import regex
94
+ // (`[\w.]+`) does not match `*`, so `import com.acme.infrastructure.*;` is
95
+ // absent from `adapter.imports` entirely. Measured, not assumed.
96
+ //
97
+ // The design's §4.3 claimed R15 would still catch a wildcard via its package
98
+ // segments. That is not what the parser does, so the claim is corrected here
99
+ // rather than left as documentation that disagrees with the code.
100
+ it('AC-728-14b: 通配 import 不会出现在 adapter.imports 中,因此任何规则都看不到它', () => {
101
+ const wildcardSource = 'import com.acme.infrastructure.*;';
102
+ // Mirror the adapter's own regex so this test breaks if that regex widens.
103
+ const adapterImportRegex = /^\s*import\s+(?:static\s+)?([\w.]+)\s*;\s*$/;
104
+ expect(adapterImportRegex.exec(wildcardSource)).toBeNull();
105
+ // And with an empty import list, R15 stays silent.
106
+ expect(domainEventRule.check(EVENT_FILE, adapter([]) as never)).toEqual([]);
107
+ });
108
+ });
109
+
110
+ describe('W01 — Util/Helper 不应依赖 Application Service(WARNING)', () => {
111
+ const UTIL_FILE = 'src/main/java/com/acme/shared/StringUtils.java';
112
+
113
+ it('AC-728-06: StringUtils import OrderService -> 告警', () => {
114
+ const v = utilServiceRule.check(UTIL_FILE, adapter(['com.acme.application.service.OrderService']) as never);
115
+ expect(v).toHaveLength(1);
116
+ expect(v[0].ruleId).toBe('arch.util-service');
117
+ expect(v[0].severity).toBe('warning');
118
+ });
119
+
120
+ it('AC-728-07: FileHelper import java.io.* -> 通过', () => {
121
+ const v = utilServiceRule.check(
122
+ 'src/main/java/com/acme/shared/FileHelper.java',
123
+ adapter(['java.io.File', 'java.util.List']) as never,
124
+ );
125
+ expect(v).toEqual([]);
126
+ });
127
+
128
+ // Framework services are not this project's application layer. Paired with
129
+ // AC-728-13 below, these two prove the exclusion is scoped to framework
130
+ // prefixes and does not silence the project's own services.
131
+ it('AC-728-12: OrderHelper import Spring 的 DiscoveryService -> 不报(框架包排除)', () => {
132
+ const v = utilServiceRule.check(
133
+ 'src/main/java/com/acme/shared/OrderHelper.java',
134
+ adapter(['org.springframework.cloud.client.discovery.DiscoveryService']) as never,
135
+ );
136
+ expect(v).toEqual([]);
137
+ });
138
+
139
+ it('AC-728-13: OrderHelper import 本项目的 OrderService -> 报(排除只对框架包生效)', () => {
140
+ const v = utilServiceRule.check(
141
+ 'src/main/java/com/acme/shared/OrderHelper.java',
142
+ adapter(['com.acme.application.service.OrderService']) as never,
143
+ );
144
+ expect(v).toHaveLength(1);
145
+ });
146
+ });
147
+
148
+ describe('W01 不得阻塞提交', () => {
149
+ // "Not blocking" is not "silent": the two assertions below are deliberately
150
+ // separate. An implementation that swallowed W01 entirely would pass the
151
+ // first and fail the second (AC-728-10 / AC-728-11).
152
+ it('AC-728-10: W01 产出中没有 error 级违规', () => {
153
+ const v = utilServiceRule.check(
154
+ 'src/main/java/com/acme/shared/StringUtils.java',
155
+ adapter(['com.acme.application.service.OrderService']) as never,
156
+ );
157
+ expect(v.every((violation) => violation.severity !== 'error')).toBe(true);
158
+ });
159
+
160
+ it('AC-728-11: W01 仍然出现在结果里(不阻塞 != 不上报)', () => {
161
+ const v = utilServiceRule.check(
162
+ 'src/main/java/com/acme/shared/StringUtils.java',
163
+ adapter(['com.acme.application.service.OrderService']) as never,
164
+ );
165
+ expect(v.length).toBeGreaterThan(0);
166
+ });
167
+
168
+ it('AC-728-08: W01 默认规则配置为 warning', () => {
169
+ expect(utilServiceRule.severity).toBe('warning');
170
+ });
171
+ });
172
+
173
+ describe('src/test/java 整体排除', () => {
174
+ // Test sources may be named anything; the rules constrain production layering.
175
+ it('测试目录下的同名依赖不触发任何规则', () => {
176
+ const testFile = 'src/test/java/com/acme/interfaces/dto/UserDTOTest.java';
177
+ expect(dtoLayeringRule.check(testFile, adapter(['com.acme.application.service.UserService']) as never)).toEqual([]);
178
+ expect(utilServiceRule.check('src/test/java/com/acme/StringUtilsTest.java', adapter(['com.acme.application.service.OrderService']) as never)).toEqual([]);
179
+ });
180
+ });
@@ -0,0 +1,133 @@
1
+ /**
2
+ * @test REQ-727
3
+ * @intent Java 命名规则 R10/R11/R12 —— 按包路径约束类名后缀。
4
+ * ArchUnit 33 条里这三条是纯 AST 模式匹配,不需要跑 Maven,
5
+ * 因此能在 pre-commit 拦住,比 ArchUnit 快一个数量级。
6
+ * @covers AC-727-01 AC-727-02 AC-727-03 AC-727-04 AC-727-05 AC-727-06 AC-727-07 AC-727-08
7
+ */
8
+ import { describe, it, expect } from 'vitest';
9
+ import { Rule, Violation } from '../../../types';
10
+ import {
11
+ controllerNamingRule,
12
+ serviceNamingRule,
13
+ repositoryNamingRule,
14
+ } from '../naming';
15
+ import { extractPackageSegments } from '../shared';
16
+
17
+ /** Minimal adapter surface the naming rules read: class names + positions. */
18
+ function adapterWithClasses(classes: Array<{ name: string; line?: number }>) {
19
+ return { extractClasses: () => classes };
20
+ }
21
+
22
+ /** Call a rule and return only its violations, so each test reads as one assertion. */
23
+ function violationsOf(
24
+ rule: Rule,
25
+ file: string,
26
+ classes: Array<{ name: string; line?: number }>,
27
+ ): Violation[] {
28
+ return rule.check(file, adapterWithClasses(classes) as never);
29
+ }
30
+
31
+ describe('R10 — interfaces/rest 下的类必须以 Controller 结尾', () => {
32
+ it('AC-727-01: UserAPI 在 interfaces/rest 下 -> 违规', () => {
33
+ const v = violationsOf(
34
+ controllerNamingRule,
35
+ 'src/main/java/com/acme/interfaces/rest/UserAPI.java',
36
+ [{ name: 'UserAPI' }],
37
+ );
38
+ expect(v).toHaveLength(1);
39
+ expect((v[0] as { ruleId: string }).ruleId).toBe('arch.controller');
40
+ });
41
+
42
+ it('AC-727-02: UserController 在 interfaces/rest 下 -> 通过', () => {
43
+ const v = violationsOf(
44
+ controllerNamingRule,
45
+ 'src/main/java/com/acme/interfaces/rest/UserController.java',
46
+ [{ name: 'UserController' }],
47
+ );
48
+ expect(v).toEqual([]);
49
+ });
50
+ });
51
+
52
+ describe('R11 — application/service 下的类必须以 Service 或 ServiceImpl 结尾', () => {
53
+ it('AC-727-03: OrderManager 在 application/service 下 -> 违规', () => {
54
+ const v = violationsOf(
55
+ serviceNamingRule,
56
+ 'src/main/java/com/acme/application/service/OrderManager.java',
57
+ [{ name: 'OrderManager' }],
58
+ );
59
+ expect(v).toHaveLength(1);
60
+ expect((v[0] as { ruleId: string }).ruleId).toBe('arch.service');
61
+ });
62
+
63
+ it('AC-727-04: OrderServiceImpl 在 application/service 下 -> 通过', () => {
64
+ const v = violationsOf(
65
+ serviceNamingRule,
66
+ 'src/main/java/com/acme/application/service/OrderServiceImpl.java',
67
+ [{ name: 'OrderServiceImpl' }],
68
+ );
69
+ expect(v).toEqual([]);
70
+ });
71
+ });
72
+
73
+ describe('R12 — infrastructure/repository 与 gateway 下的类必须以 Mapper/DAO/Repository 结尾', () => {
74
+ // The suffix whitelist is case-SENSITIVE on purpose: `DAO` is the documented
75
+ // form, so `UserDao` must be reported. Lower-casing before comparison would
76
+ // silently accept it and the rule would stop enforcing the standard.
77
+ it('AC-727-05: UserDao 在 infrastructure/repository 下 -> 违规(DAO 大写才算)', () => {
78
+ const v = violationsOf(
79
+ repositoryNamingRule,
80
+ 'src/main/java/com/acme/infrastructure/repository/UserDao.java',
81
+ [{ name: 'UserDao' }],
82
+ );
83
+ expect(v).toHaveLength(1);
84
+ expect((v[0] as { ruleId: string }).ruleId).toBe('arch.repository');
85
+ });
86
+
87
+ it('AC-727-06: UserMapper 在 infrastructure/repository 下 -> 通过', () => {
88
+ const v = violationsOf(
89
+ repositoryNamingRule,
90
+ 'src/main/java/com/acme/infrastructure/repository/UserMapper.java',
91
+ [{ name: 'UserMapper' }],
92
+ );
93
+ expect(v).toEqual([]);
94
+ });
95
+ });
96
+
97
+ describe('包路径边界', () => {
98
+ // Maven multi-module puts the module name before src/main/java. Anchoring the
99
+ // match on the start of the path (or on "src/main/java" as a prefix) would
100
+ // miss every class in every submodule -- the common shape, not an edge case.
101
+ it('AC-727-07: Maven 多模块路径 core/src/main/java/... 正确识别为 interfaces/rest', () => {
102
+ const v = violationsOf(
103
+ controllerNamingRule,
104
+ 'core/src/main/java/com/acme/interfaces/rest/UserAPI.java',
105
+ [{ name: 'UserAPI' }],
106
+ );
107
+ expect(v).toHaveLength(1);
108
+ });
109
+
110
+ // The case above does NOT pin down WHICH `src/.../java` is used: it holds a
111
+ // single occurrence, so "first" and "last" agree. A mutation run proved this:
112
+ // flipping the anchor to the first occurrence left every test green.
113
+ //
114
+ // Asserting through a rule cannot fix that, because the rules search for a
115
+ // CONTIGUOUS run (`interfaces/rest`), and both anchors still contain it. So
116
+ // this checks the extracted package directly -- the only assertion that
117
+ // actually distinguishes the two behaviours.
118
+ it('AC-727-07b: 路径含两处 src/main/java 时锚定最后一处(嵌套模块)', () => {
119
+ expect(
120
+ extractPackageSegments(
121
+ 'legacy/src/main/java/gen/src/main/java/com/acme/interfaces/rest/UserAPI.java',
122
+ ),
123
+ ).toEqual(['com', 'acme', 'interfaces', 'rest']);
124
+ });
125
+
126
+ it('AC-727-08: 非目标包 util/FooHelper.java 不误报任何命名规则', () => {
127
+ const file = 'src/main/java/com/acme/util/FooHelper.java';
128
+ const classes = [{ name: 'FooHelper' }];
129
+ expect(violationsOf(controllerNamingRule, file, classes)).toEqual([]);
130
+ expect(violationsOf(serviceNamingRule, file, classes)).toEqual([]);
131
+ expect(violationsOf(repositoryNamingRule, file, classes)).toEqual([]);
132
+ });
133
+ });