@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
@@ -0,0 +1,113 @@
1
+ /**
2
+ * @test REQ-727
3
+ * @intent shared.ts 是 arch 两组规则的公共基础:包路径提取、类名/import 读取、
4
+ * severity 回退。这些函数一旦错了,上面的规则会以「没有任何违规」的
5
+ * 方式静默失效——所以单独钉住,而不是只靠规则测试间接覆盖。
6
+ * @covers AC-727-07 AC-726-01
7
+ */
8
+ import { describe, it, expect } from 'vitest';
9
+ import {
10
+ extractPackageSegments,
11
+ isTestSource,
12
+ classNamesOf,
13
+ importsOf,
14
+ readSeverity,
15
+ simpleNameOf,
16
+ packageSegmentsOf,
17
+ } from '../shared';
18
+
19
+ describe('extractPackageSegments — 从路径取包', () => {
20
+ it('标准 Maven 布局:src/main/java/<pkg>/File.java', () => {
21
+ expect(extractPackageSegments('src/main/java/com/acme/order/Order.java')).toEqual([
22
+ 'com',
23
+ 'acme',
24
+ 'order',
25
+ ]);
26
+ });
27
+
28
+ it('多模块布局:模块名不算进包名', () => {
29
+ expect(
30
+ extractPackageSegments('core/src/main/java/com/acme/interfaces/rest/UserAPI.java'),
31
+ ).toEqual(['com', 'acme', 'interfaces', 'rest']);
32
+ });
33
+
34
+ it('含两处 src/main/java 时锚定最后一处', () => {
35
+ expect(
36
+ extractPackageSegments('legacy/src/main/java/gen/src/main/java/com/acme/A.java'),
37
+ ).toEqual(['com', 'acme']);
38
+ });
39
+
40
+ it('Windows 反斜杠路径同样处理', () => {
41
+ expect(
42
+ extractPackageSegments('core\\src\\main\\java\\com\\acme\\interfaces\\rest\\A.java'),
43
+ ).toEqual(['com', 'acme', 'interfaces', 'rest']);
44
+ });
45
+
46
+ it('非 Java 源根路径返回空数组(规则据此不触发,而不是猜)', () => {
47
+ expect(extractPackageSegments('src/com/acme/A.java')).toEqual([]);
48
+ expect(extractPackageSegments('README.md')).toEqual([]);
49
+ });
50
+ });
51
+
52
+ describe('isTestSource — 测试目录整体排除', () => {
53
+ it('src/test/java 判定为测试代码', () => {
54
+ expect(isTestSource('src/test/java/com/acme/A.java')).toBe(true);
55
+ expect(isTestSource('core/src/test/java/com/acme/ATest.java')).toBe(true);
56
+ });
57
+
58
+ it('src/main/java 不是测试代码', () => {
59
+ expect(isTestSource('src/main/java/com/acme/A.java')).toBe(false);
60
+ });
61
+ });
62
+
63
+ describe('classNamesOf / importsOf — 跳过不可用条目', () => {
64
+ it('跳过没有 name 或 name 为空的条目', () => {
65
+ // Named so the "no name" case reads as intentional rather than as a stray
66
+ // number: 3 is the line an entry carries when it has no name to report.
67
+ const UNNAMED_ENTRY_LINE = 3;
68
+ const adapter = {
69
+ extractClasses: () => [
70
+ { name: 'A', line: 1 },
71
+ { name: '' },
72
+ { line: UNNAMED_ENTRY_LINE },
73
+ { name: 'B' },
74
+ ],
75
+ get imports() {
76
+ return [{ name: 'a.B', line: 2 }, {}, { name: '' }];
77
+ },
78
+ };
79
+ expect(classNamesOf(adapter)).toEqual([{ name: 'A', line: 1 }, { name: 'B', line: undefined }]);
80
+ expect(importsOf(adapter)).toEqual([{ name: 'a.B', line: 2 }]);
81
+ });
82
+
83
+ it('adapter 缺少对应成员时返回空数组而不抛错', () => {
84
+ expect(classNamesOf({})).toEqual([]);
85
+ expect(importsOf({})).toEqual([]);
86
+ });
87
+ });
88
+
89
+ describe('readSeverity — 缺失配置时回退', () => {
90
+ it('读取已配置的 severity', () => {
91
+ expect(readSeverity({ 'x': { severity: 'info' } }, 'x', 'error')).toBe('info');
92
+ });
93
+
94
+ it('分组整体缺失时回退到默认(老配置无 arch 键的场景)', () => {
95
+ expect(readSeverity(undefined, 'x', 'warning')).toBe('warning');
96
+ });
97
+
98
+ it('非法 severity 值回退到默认,而不是透传', () => {
99
+ expect(readSeverity({ 'x': { severity: 'fatal' } }, 'x', 'error')).toBe('error');
100
+ });
101
+ });
102
+
103
+ describe('simpleNameOf / packageSegmentsOf', () => {
104
+ it('取全限定名的简单类名与包段', () => {
105
+ expect(simpleNameOf('com.acme.order.OrderService')).toBe('OrderService');
106
+ expect(packageSegmentsOf('com.acme.order.OrderService')).toEqual(['com', 'acme', 'order']);
107
+ });
108
+
109
+ it('无包名的裸类名:简单名是自身,包段为空', () => {
110
+ expect(simpleNameOf('OrderService')).toBe('OrderService');
111
+ expect(packageSegmentsOf('OrderService')).toEqual([]);
112
+ });
113
+ });
@@ -0,0 +1,264 @@
1
+ import { Rule, Violation, Severity } from '../../types';
2
+ import { getActiveConfig } from '../../config';
3
+ import {
4
+ extractPackageSegments,
5
+ isTestSource,
6
+ classNamesOf,
7
+ importsOf,
8
+ readSeverity,
9
+ simpleNameOf,
10
+ packageSegmentsOf,
11
+ } from './shared';
12
+
13
+ /**
14
+ * ARCH-12 (#699) — Java dependency-direction rules R08 / R15 / W01.
15
+ *
16
+ * Three rules, all answerable from the file path plus the import list, so they
17
+ * run in pre-commit rather than behind `mvn test`.
18
+ *
19
+ * ## What each rule judges, and why they judge it differently
20
+ *
21
+ * The three deliberately do NOT use the same signal, and that is not an
22
+ * inconsistency to be tidied away:
23
+ *
24
+ * - **R08** judges the imported CLASS NAME. It forbids "a DTO depends on a
25
+ * service", and service/repository classes are named differently in every
26
+ * project's package scheme, so no fixed package path can express it.
27
+ * - **R15** judges PACKAGE SEGMENTS on both sides. "The domain-event layer must
28
+ * not depend on the infrastructure layer" is a statement about the layer
29
+ * structure this standard prescribes, and a layer is defined by its package.
30
+ * - **W01** judges the source FILE NAME plus the imported CLASS NAME.
31
+ *
32
+ * So R08 rejecting package-path matching is not contradicted by R15 using it:
33
+ * R08 rejects *guessing a dependency's role from its package*, not package
34
+ * matching in general.
35
+ */
36
+
37
+ const DTO_RULE_ID = 'arch.dto-layering';
38
+ const DOMAIN_EVENT_RULE_ID = 'arch.domain-event';
39
+ const UTIL_SERVICE_RULE_ID = 'arch.util-service';
40
+
41
+ /** Class-name suffixes that make an import a "service" for R08/W01 purposes. */
42
+ const SERVICE_SUFFIXES = ['Service', 'ServiceImpl'];
43
+ /** Class-name suffixes that make an import a "repository" for R08 purposes. */
44
+ const REPOSITORY_SUFFIXES = ['Repository', 'Mapper', 'DAO'];
45
+
46
+ /**
47
+ * Suffixes that DISQUALIFY a match, checked BEFORE the suffix hit.
48
+ *
49
+ * Without this list `OrderServiceConstants` and `PaymentServiceFacade` match
50
+ * `*Service` and get reported as service dependencies, which they are not. The
51
+ * exclusions are what make the suffix heuristic usable on a real codebase --
52
+ * see AC-699-09. Do not delete this as "redundant with SERVICE_SUFFIXES".
53
+ */
54
+ const EXCLUDED_SUFFIXES = [
55
+ 'Constants',
56
+ 'Facade',
57
+ 'Config',
58
+ 'Exception',
59
+ 'Test',
60
+ 'Factory',
61
+ 'Builder',
62
+ 'DTO',
63
+ 'VO',
64
+ 'Util',
65
+ ];
66
+
67
+ /**
68
+ * Framework package prefixes whose types are provided by a library, not by the
69
+ * project's application layer.
70
+ *
71
+ * `DiscoveryService` matches `*Service` but comes from Spring, so warning that
72
+ * an `OrderHelper` depends on it is pure noise (AC-699-12). A closed list, not
73
+ * a user-maintained allowlist: it can grow with real reports, but it never asks
74
+ * a project to maintain it before the rule is useful.
75
+ */
76
+ const FRAMEWORK_PREFIXES = [
77
+ 'java.',
78
+ 'javax.',
79
+ 'jakarta.',
80
+ 'org.springframework.',
81
+ 'com.fasterxml.',
82
+ 'com.google.',
83
+ 'org.apache.',
84
+ ];
85
+
86
+ /** Class-name suffixes that make a source file a "utility" for W01. */
87
+ const UTIL_SOURCE_SUFFIXES = ['Util', 'Utils', 'Helper'];
88
+
89
+ /** The DTO / VO suffixes R08 constrains. */
90
+ const DTO_SUFFIXES = ['DTO', 'Dto', 'VO'];
91
+
92
+ /** The file's base name without the `.java` extension (`.../UserDTO.java` -> `UserDTO`). */
93
+ function baseNameOf(file: string): string {
94
+ const name = file.split('\\').join('/').split('/').pop() ?? '';
95
+ return name.replace(/\.java$/i, '');
96
+ }
97
+
98
+ /** Whether `name` ends with any of `suffixes`. Case-sensitive by design. */
99
+ function endsWithAny(name: string, suffixes: string[]): boolean {
100
+ return suffixes.some((suffix) => name.endsWith(suffix));
101
+ }
102
+
103
+ /**
104
+ * Whether an imported type counts as a service/repository at all.
105
+ *
106
+ * The exclusion check runs first so that a disqualified name is never treated
107
+ * as a dependency violation, however many suffixes it happens to match.
108
+ */
109
+ function dependencyRole(fullyQualified: string): 'service' | 'repository' | null {
110
+ const simpleName = simpleNameOf(fullyQualified);
111
+ if (endsWithAny(simpleName, EXCLUDED_SUFFIXES)) return null;
112
+ if (endsWithAny(simpleName, SERVICE_SUFFIXES)) return 'service';
113
+ if (endsWithAny(simpleName, REPOSITORY_SUFFIXES)) return 'repository';
114
+ return null;
115
+ }
116
+
117
+ /** Whether an imported type comes from a framework/library package. */
118
+ function isFrameworkType(fullyQualified: string): boolean {
119
+ return FRAMEWORK_PREFIXES.some((prefix) => fullyQualified.startsWith(prefix));
120
+ }
121
+
122
+ /**
123
+ * Build the violation list for one file, skipping test sources.
124
+ *
125
+ * `src/test/java` is excluded wholesale: a test may be named anything, and the
126
+ * dependency rules constrain production layering only.
127
+ */
128
+ function checkFile(
129
+ file: string,
130
+ adapter: unknown,
131
+ ruleId: string,
132
+ severity: Severity,
133
+ judge: (facts: {
134
+ classes: Array<{ name: string; line?: number }>;
135
+ imports: Array<{ name: string; line?: number }>;
136
+ packageSegments: string[];
137
+ }) => Array<{ line: number; message: string }>,
138
+ ): Violation[] {
139
+ if (isTestSource(file)) return [];
140
+ const hits = judge({
141
+ classes: classNamesOf(adapter),
142
+ imports: importsOf(adapter),
143
+ packageSegments: extractPackageSegments(file),
144
+ });
145
+ return hits.map((hit) => ({
146
+ file,
147
+ line: hit.line,
148
+ ruleId,
149
+ message: hit.message,
150
+ severity,
151
+ }));
152
+ }
153
+
154
+ /**
155
+ * R08 — a DTO/VO must not import a service or a repository.
156
+ *
157
+ * Wildcard imports (`import com.acme.service.*;`) never reach here: the Java
158
+ * adapter's import regex does not capture `*`, so the import list simply does
159
+ * not contain them. That is the behaviour AC-699-14 pins down, and it is the
160
+ * safer default -- a wildcard gives no class name to judge, and guessing one
161
+ * from the package is exactly the false-positive source this rule avoids.
162
+ */
163
+ export const dtoLayeringRule: Rule = {
164
+ id: DTO_RULE_ID,
165
+ name: 'DTO Dependency Layering Rule (R08)',
166
+ threshold: 0,
167
+ severity: 'error',
168
+ check: (file: string, adapter: unknown): Violation[] => {
169
+ const severity = readSeverity(getActiveConfig().rules.arch, 'dto-layering', 'error');
170
+ return checkFile(file, adapter, DTO_RULE_ID, severity, ({ imports }) => {
171
+ // Judged on the FILE name, not on extractClasses(): the question is
172
+ // "is this file a DTO", and the file name is what carries a DTO's
173
+ // identity. Requiring a parsed class would make the rule depend on the
174
+ // adapter succeeding, and would go blind on a file the parser trips on.
175
+ const sourceName = baseNameOf(file);
176
+ if (!endsWithAny(sourceName, DTO_SUFFIXES)) return [];
177
+ const hits: Array<{ line: number; message: string }> = [];
178
+ for (const imp of imports) {
179
+ const role = dependencyRole(imp.name);
180
+ if (role === null) continue;
181
+ const target = simpleNameOf(imp.name);
182
+ hits.push({
183
+ line: imp.line ?? 1,
184
+ message:
185
+ `DTO "${sourceName}" must not depend on ${role} "${target}" ` +
186
+ `(imported from ${imp.name})`,
187
+ });
188
+ }
189
+ return hits;
190
+ });
191
+ },
192
+ };
193
+
194
+ /**
195
+ * R15 — a class in `domain/event` must not import from `infrastructure`.
196
+ *
197
+ * Judged on package segments, so a wildcard import IS caught here: the import
198
+ * `com.acme.infrastructure.*` carries the layer name even without a class name.
199
+ */
200
+ export const domainEventRule: Rule = {
201
+ id: DOMAIN_EVENT_RULE_ID,
202
+ name: 'Domain Event Dependency Rule (R15)',
203
+ threshold: 0,
204
+ severity: 'error',
205
+ check: (file: string, adapter: unknown): Violation[] => {
206
+ const severity = readSeverity(getActiveConfig().rules.arch, 'domain-event', 'error');
207
+ return checkFile(file, adapter, DOMAIN_EVENT_RULE_ID, severity, ({ imports, packageSegments }) => {
208
+ const inDomainEvent =
209
+ packageSegments.includes('domain') && packageSegments.includes('event');
210
+ if (!inDomainEvent) return [];
211
+ const hits: Array<{ line: number; message: string }> = [];
212
+ for (const imp of imports) {
213
+ if (!packageSegmentsOf(imp.name).includes('infrastructure')) continue;
214
+ hits.push({
215
+ line: imp.line ?? 1,
216
+ message:
217
+ `Domain event must not depend on the infrastructure layer ` +
218
+ `(imported from ${imp.name})`,
219
+ });
220
+ }
221
+ return hits;
222
+ });
223
+ },
224
+ };
225
+
226
+ /**
227
+ * W01 — a `*Util` / `*Utils` / `*Helper` should not depend on an application
228
+ * service. WARNING only: it must never block a commit (AC-699-08), but it must
229
+ * still be REPORTED (AC-699-11) -- "not blocking" is not "silent".
230
+ */
231
+ export const utilServiceRule: Rule = {
232
+ id: UTIL_SERVICE_RULE_ID,
233
+ name: 'Utility Service Dependency Rule (W01)',
234
+ threshold: 0,
235
+ severity: 'warning',
236
+ check: (file: string, adapter: unknown): Violation[] => {
237
+ const severity = readSeverity(getActiveConfig().rules.arch, 'util-service', 'warning');
238
+ const sourceName = file.replace(/\\/g, '/').split('/').pop() ?? '';
239
+ const baseName = sourceName.replace(/\.java$/i, '');
240
+ if (!endsWithAny(baseName, UTIL_SOURCE_SUFFIXES)) return [];
241
+ return checkFile(file, adapter, UTIL_SERVICE_RULE_ID, severity, ({ imports }) => {
242
+ const hits: Array<{ line: number; message: string }> = [];
243
+ for (const imp of imports) {
244
+ // Framework services are not this project's application layer; skipping
245
+ // them is what keeps AC-699-12 quiet.
246
+ if (isFrameworkType(imp.name)) continue;
247
+ if (dependencyRole(imp.name) !== 'service') continue;
248
+ hits.push({
249
+ line: imp.line ?? 1,
250
+ message:
251
+ `Utility "${baseName}" should not depend on application service ` +
252
+ `"${simpleNameOf(imp.name)}" (imported from ${imp.name})`,
253
+ });
254
+ }
255
+ return hits;
256
+ });
257
+ },
258
+ };
259
+
260
+ export const archDependencyRules: Rule[] = [
261
+ dtoLayeringRule,
262
+ domainEventRule,
263
+ utilServiceRule,
264
+ ];
@@ -0,0 +1,188 @@
1
+ import { Rule, Violation, Severity } from '../../types';
2
+ import { getActiveConfig } from '../../config';
3
+ import { extractPackageSegments, classNamesOf, readSeverity, isUnrecognisedJavaLayout } from './shared';
4
+
5
+ /**
6
+ * ARCH-07 (#694) — Java naming rules R10 / R11 / R12.
7
+ *
8
+ * These are the only three of the 33 ArchUnit rules that need nothing but the
9
+ * file path and the class names, so they run in pre-commit instead of waiting
10
+ * for Maven. That is the whole point: the expensive rules live behind
11
+ * `mvn test` and therefore rarely run locally.
12
+ *
13
+ * The package is read from the FILE PATH, not from the `package` declaration or
14
+ * an import. A path is what the hook actually has, it survives files whose
15
+ * package statement disagrees with their location (a real and common mistake),
16
+ * and it works before the file compiles.
17
+ */
18
+
19
+ /** Rule ids. Namespaced `arch.*` so they group apart from clean-code and solid. */
20
+ const CONTROLLER_RULE_ID = 'arch.controller';
21
+ const SERVICE_RULE_ID = 'arch.service';
22
+ const REPOSITORY_RULE_ID = 'arch.repository';
23
+
24
+ /** The controller package, relative to the source root. */
25
+ const CONTROLLER_PACKAGE = ['interfaces', 'rest'];
26
+ /** The service package, relative to the source root. */
27
+ const SERVICE_PACKAGE = ['application', 'service'];
28
+ /** The two persistence packages that share one naming rule. */
29
+ const REPOSITORY_PACKAGES = [
30
+ ['infrastructure', 'repository'],
31
+ ['infrastructure', 'gateway'],
32
+ ];
33
+
34
+ /**
35
+ * Whether `segments` contains `wanted` as a contiguous run.
36
+ *
37
+ * A contiguous run, not a set: `interfaces/rest` must match a package that
38
+ * reads exactly that way. Treating it as a set would also match
39
+ * `rest/interfaces`, which is a different package.
40
+ */
41
+ function containsRun(segments: string[], wanted: string[]): boolean {
42
+ for (let start = 0; start + wanted.length <= segments.length; start += 1) {
43
+ let matched = true;
44
+ for (let offset = 0; offset < wanted.length; offset += 1) {
45
+ if (segments[start + offset] !== wanted[offset]) {
46
+ matched = false;
47
+ break;
48
+ }
49
+ }
50
+ if (matched) return true;
51
+ }
52
+ return false;
53
+ }
54
+
55
+ /** Whether a class name ends with any of `suffixes`. Case-sensitive by design. */
56
+ function endsWithAny(name: string, suffixes: string[]): boolean {
57
+ return suffixes.some((suffix) => name.endsWith(suffix));
58
+ }
59
+
60
+ /**
61
+ * Build one naming rule.
62
+ *
63
+ * All three share the same shape: "inside package P, every class name must end
64
+ * with one of S". Writing them once, parameterised, keeps the package-matching
65
+ * and severity-reading logic from drifting between the three.
66
+ */
67
+ /**
68
+ * The `info` finding a naming rule reports for a file it could not judge.
69
+ *
70
+ * Returns null when the layout IS recognised, so the rule proceeds normally.
71
+ * Kept as a separate function so the shared `check()` body stays readable: the
72
+ * skip path is one concern, the naming test is another.
73
+ *
74
+ * Deliberately consulted BEFORE the package-scope test. `inScope` asks "is this
75
+ * package in my remit?", not "should this file be analysed" -- the analyzer has
76
+ * already applied the user's path filters before calling `check()`. Do not add
77
+ * path filtering inside a rule, or this diagnostic would bypass those filters.
78
+ */
79
+ function unrecognisedLayoutFinding(file: string, ruleId: string): Violation | null {
80
+ if (!isUnrecognisedJavaLayout(file)) return null;
81
+ return {
82
+ file,
83
+ line: 1,
84
+ ruleId,
85
+ message:
86
+ `Skipped: ${file} has no recognisable Java source root, so this rule ` +
87
+ 'could not judge it. Use a standard src/<scope>/java layout, or read ' +
88
+ 'this empty result as "not examined" rather than "no violations".',
89
+ severity: 'info',
90
+ };
91
+ }
92
+
93
+ function buildNamingRule(options: {
94
+ id: string;
95
+ name: string;
96
+ /** Package runs; a class is in scope when ANY of them matches. */
97
+ packages: string[][];
98
+ suffixes: string[];
99
+ /** Human-readable package description used in the message. */
100
+ packageLabel: string;
101
+ /** Shown after "must end with", already joined for display. */
102
+ suffixLabel: string;
103
+ configKey: 'controller' | 'service' | 'repository';
104
+ }): Rule {
105
+ return {
106
+ id: options.id,
107
+ name: options.name,
108
+ threshold: 0,
109
+ severity: 'error',
110
+ check: (file: string, adapter: unknown): Violation[] => {
111
+ // Read the ACTIVE config per invocation; a module-load snapshot was #457.
112
+ const severity: Severity = readSeverity(
113
+ getActiveConfig().rules.arch,
114
+ options.configKey,
115
+ 'error',
116
+ );
117
+
118
+ // A Java/Kotlin file whose source root we cannot read yields no segments,
119
+ // so the package test below never matches and this rule silently reports
120
+ // nothing -- which reads as "clean". Announce the skip instead.
121
+ const skipped = unrecognisedLayoutFinding(file, options.id);
122
+ if (skipped) return [skipped];
123
+
124
+ const segments = extractPackageSegments(file);
125
+ const inScope = options.packages.some((wanted) => containsRun(segments, wanted));
126
+ // Out-of-scope files are the common case; bail before touching the adapter.
127
+ if (!inScope) return [];
128
+
129
+ return classNamesOf(adapter)
130
+ .filter((cls) => !endsWithAny(cls.name, options.suffixes))
131
+ .map((cls) => ({
132
+ file,
133
+ line: cls.line ?? 1,
134
+ ruleId: options.id,
135
+ message:
136
+ `Class "${cls.name}" in ${options.packageLabel} must end with ` +
137
+ `${options.suffixLabel} (found "${cls.name}")`,
138
+ severity,
139
+ }));
140
+ },
141
+ };
142
+ }
143
+
144
+ /** R10 — classes in `interfaces/rest` must be `*Controller`. */
145
+ export const controllerNamingRule: Rule = buildNamingRule({
146
+ id: CONTROLLER_RULE_ID,
147
+ name: 'Controller Naming Rule (R10)',
148
+ packages: [CONTROLLER_PACKAGE],
149
+ suffixes: ['Controller'],
150
+ packageLabel: 'interfaces/rest',
151
+ suffixLabel: '"Controller"',
152
+ configKey: 'controller',
153
+ });
154
+
155
+ /** R11 — classes in `application/service` must be `*Service` or `*ServiceImpl`. */
156
+ export const serviceNamingRule: Rule = buildNamingRule({
157
+ id: SERVICE_RULE_ID,
158
+ name: 'Service Naming Rule (R11)',
159
+ packages: [SERVICE_PACKAGE],
160
+ // `ServiceImpl` is listed explicitly rather than implied by `Service`:
161
+ // it documents that both forms are sanctioned, and a future reader cannot
162
+ // mistake `Service` alone for the whole intent.
163
+ suffixes: ['Service', 'ServiceImpl'],
164
+ packageLabel: 'application/service',
165
+ suffixLabel: '"Service" or "ServiceImpl"',
166
+ configKey: 'service',
167
+ });
168
+
169
+ /** R12 — classes in `infrastructure/repository` or `.../gateway` must be persistence-named. */
170
+ export const repositoryNamingRule: Rule = buildNamingRule({
171
+ id: REPOSITORY_RULE_ID,
172
+ name: 'Repository Naming Rule (R12)',
173
+ packages: REPOSITORY_PACKAGES,
174
+ // `DAO` is uppercase because that is the documented form. `Dao` is NOT
175
+ // accepted, and the case sensitivity is deliberate: see AC-694-05, where
176
+ // `UserDao` must be reported. Lower-casing here would make the rule accept
177
+ // the very name the standard rejects.
178
+ suffixes: ['Mapper', 'DAO', 'Repository'],
179
+ packageLabel: 'infrastructure/repository or infrastructure/gateway',
180
+ suffixLabel: '"Mapper", "DAO" or "Repository"',
181
+ configKey: 'repository',
182
+ });
183
+
184
+ export const archNamingRules: Rule[] = [
185
+ controllerNamingRule,
186
+ serviceNamingRule,
187
+ repositoryNamingRule,
188
+ ];