@boyingliu01/xp-gate 0.37.3 → 0.38.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 (116) hide show
  1. package/adapter-common.sh +12 -2
  2. package/adapters/csharp.sh +73 -2
  3. package/adapters/dart.sh +13 -0
  4. package/adapters/go.sh +5 -0
  5. package/adapters/iac.sh +46 -3
  6. package/adapters/java.sh +6 -0
  7. package/adapters/kotlin.sh +6 -0
  8. package/adapters/shell.sh +119 -34
  9. package/adapters/swift.sh +6 -0
  10. package/adapters/typescript.sh +98 -34
  11. package/bin/xp-gate.js +48 -2
  12. package/gate-10.sh +99 -26
  13. package/gate-12-file-hygiene.sh +13 -1
  14. package/gate-registry.sh +197 -0
  15. package/gates/python-health.ts +67 -29
  16. package/hooks/adapter-common.sh +12 -2
  17. package/hooks/deploy-manifest.sh +100 -0
  18. package/hooks/gate-10.sh +99 -26
  19. package/hooks/gate-12-file-hygiene.sh +13 -1
  20. package/hooks/gate-driver.sh +120 -0
  21. package/hooks/gate-entries/gate-0-entry.sh +825 -0
  22. package/hooks/gate-entries/gate-1-entry.sh +767 -0
  23. package/hooks/gate-entries/gate-10-entry.sh +52 -0
  24. package/hooks/gate-entries/gate-11-entry.sh +120 -0
  25. package/hooks/gate-entries/gate-12-entry.sh +44 -0
  26. package/hooks/gate-entries/gate-12b-entry.sh +178 -0
  27. package/hooks/gate-entries/gate-12c-entry.sh +80 -0
  28. package/hooks/gate-entries/gate-13-entry.sh +584 -0
  29. package/hooks/gate-entries/gate-2-entry.sh +199 -0
  30. package/hooks/gate-entries/gate-3-entry.sh +53 -0
  31. package/hooks/gate-entries/gate-4-entry.sh +46 -0
  32. package/hooks/gate-entries/gate-5-entry.sh +1729 -0
  33. package/hooks/gate-entries/gate-6-entry.sh +658 -0
  34. package/hooks/gate-entries/gate-7-entry.sh +41 -0
  35. package/hooks/gate-entries/gate-8-entry.sh +33 -0
  36. package/hooks/gate-entries/gate-9-entry.sh +307 -0
  37. package/hooks/gate-entries/subdir-restore.sh +27 -0
  38. package/hooks/gate-registry.sh +51 -15
  39. package/hooks/hook-module-resolution.sh +73 -0
  40. package/hooks/install.sh +135 -0
  41. package/hooks/lib/now-ms.sh +55 -19
  42. package/hooks/lib/toolchain-path.sh +50 -6
  43. package/hooks/pre-commit +256 -5091
  44. package/hooks/pre-push +212 -25
  45. package/lib/__tests__/arch-config-template.test.js +190 -0
  46. package/lib/__tests__/baseline-shell-scope.test.js +60 -0
  47. package/lib/__tests__/crap-cli.test.js +14 -3
  48. package/lib/__tests__/deploy-manifest-check-wired.test.js +138 -0
  49. package/lib/__tests__/deploy-manifest-completeness.test.js +151 -0
  50. package/lib/__tests__/deploy-manifest-consumers-adapter-uninstall.test.js +40 -0
  51. package/lib/__tests__/deploy-manifest-consumers-no-private-lists.test.js +74 -0
  52. package/lib/__tests__/deploy-manifest-projection.test.js +66 -0
  53. package/lib/__tests__/deploy-manifest-shell-parity.test.js +108 -0
  54. package/lib/__tests__/deploy-manifest.test.js +97 -0
  55. package/lib/__tests__/doctor.test.js +51 -7
  56. package/lib/__tests__/gate-coverage.test.js +79 -12
  57. package/lib/__tests__/gate-numbering.test.js +28 -1
  58. package/lib/__tests__/install-sh-deploy-manifest.test.js +80 -0
  59. package/lib/__tests__/mirror-sync.test.js +45 -3
  60. package/lib/__tests__/npm-package.test.js +10 -7
  61. package/lib/__tests__/sastd-client.test.js +514 -0
  62. package/lib/__tests__/shared-utils-copyHooks-manifest.test.js +69 -0
  63. package/lib/__tests__/sprint-status-rework.test.js +1 -0
  64. package/lib/arch-config-template.js +87 -0
  65. package/lib/baseline.js +54 -2
  66. package/lib/deploy-manifest.js +174 -0
  67. package/lib/doctor.js +46 -14
  68. package/lib/gate-capability.js +291 -0
  69. package/lib/gate-coverage.js +194 -74
  70. package/lib/gate-identity.js +349 -0
  71. package/lib/gate-runner.js +11 -1
  72. package/lib/hook-module-resolution.js +27 -0
  73. package/lib/init.js +72 -5
  74. package/lib/mattpocock-license-verdict.json +1 -1
  75. package/lib/sastd-client.js +572 -0
  76. package/lib/shared-utils.js +31 -9
  77. package/lib/uninstall.js +10 -7
  78. package/lib/update-hooks.js +27 -18
  79. package/mock-policy/AGENTS.md +1 -1
  80. package/mutation/AGENTS.md +1 -1
  81. package/package.json +3 -1
  82. package/plugins/claude-code/.claude-plugin/plugin.json +1 -1
  83. package/plugins/claude-code/skills/delphi-review/AGENTS.md +1 -1
  84. package/plugins/claude-code/skills/sprint-flow/AGENTS.md +1 -1
  85. package/plugins/claude-code/skills/test-specification-alignment/AGENTS.md +1 -1
  86. package/plugins/dsh/package.json +1 -1
  87. package/plugins/dsh/skills/delphi-review/AGENTS.md +1 -1
  88. package/plugins/dsh/skills/sprint-flow/AGENTS.md +1 -1
  89. package/plugins/dsh/skills/test-specification-alignment/AGENTS.md +1 -1
  90. package/plugins/opencode/package.json +1 -1
  91. package/plugins/opencode/skills/delphi-review/AGENTS.md +1 -1
  92. package/plugins/opencode/skills/sprint-flow/AGENTS.md +1 -1
  93. package/plugins/opencode/skills/test-specification-alignment/AGENTS.md +1 -1
  94. package/plugins/qoder/plugin.json +1 -1
  95. package/plugins/qoder/skills/delphi-review/AGENTS.md +1 -1
  96. package/plugins/qoder/skills/sprint-flow/AGENTS.md +1 -1
  97. package/plugins/qoder/skills/test-specification-alignment/AGENTS.md +1 -1
  98. package/principles/AGENTS.md +1 -1
  99. package/principles/__tests__/analyzer.test.ts +2 -1
  100. package/principles/__tests__/config-enforcement.test.ts +1 -0
  101. package/principles/__tests__/types.test.ts +1 -0
  102. package/principles/adapters/base.ts +14 -1
  103. package/principles/adapters/duplication.ts +134 -0
  104. package/principles/rules/__tests__/clean-code/large-file.test.ts +2 -1
  105. package/principles/rules/clean-code/code-duplication.ts +75 -9
  106. package/principles/types.ts +39 -0
  107. package/scripts/__tests__/check-mattpocock-license.test.js +36 -3
  108. package/scripts/__tests__/sync-package-content.test.js +12 -2
  109. package/scripts/generate-mirrors.cjs +125 -0
  110. package/scripts/sync-package-content.js +64 -20
  111. package/skills/delphi-review/AGENTS.md +1 -1
  112. package/skills/sprint-flow/AGENTS.md +1 -1
  113. package/skills/test-specification-alignment/AGENTS.md +1 -1
  114. package/adapters/gate-9.sh +0 -245
  115. package/gate-9.sh +0 -245
  116. package/hooks/gate-9.sh +0 -245
@@ -38,8 +38,9 @@ function getProjectHooksDir() {
38
38
  function detectLocalModifications(srcDir, hooksDestDir, adaptersDestDir) {
39
39
  const modified = [];
40
40
 
41
- // Check hook files: pre-commit, pre-push, post-merge
42
- ['pre-commit', 'pre-push', 'post-merge'].forEach(hook => {
41
+ // Check hook files — the list is the manifest's, so a hook that gets installed
42
+ // is also a hook whose local modifications get detected (REQ-DEPLOY-001).
43
+ require('./deploy-manifest.js').HOOK_FILES.forEach(hook => {
43
44
  const srcPath = path.join(srcDir, 'hooks', hook);
44
45
  const destPath = path.join(hooksDestDir, hook);
45
46
  if (fs.existsSync(destPath) && fs.existsSync(srcPath)) {
@@ -158,26 +159,34 @@ function atomicCopyFile(src, dest, dryRun, noBackup, label) {
158
159
  */
159
160
  function copyHooks(srcDir, destDir, dryRun, noBackup) {
160
161
  const hooksSrcDir = path.join(srcDir, 'hooks');
161
- ['pre-commit', 'pre-push', 'post-merge'].forEach(hook => {
162
+ // REQ-DEPLOY-001 (AC-DEPLOY-09): this listed only three hooks, so
163
+ // `update-hooks --scope hooks` produced a directory with no
164
+ // hook-module-resolution.sh — and pre-commit loads that file before any tier
165
+ // decision and fails closed, making every commit FATAL. post-commit was
166
+ // missing too (its audit-attribution flush never ran). Both now come from the
167
+ // manifest, so the installer and the updater cannot disagree again.
168
+ require('./deploy-manifest.js').HOOK_FILES.forEach(hook => {
162
169
  const src = path.join(hooksSrcDir, hook);
163
170
  const dest = path.join(destDir, hook);
164
171
  atomicCopyFile(src, dest, dryRun, noBackup, hook);
165
172
  });
166
- const libSrcDir = path.join(hooksSrcDir, 'lib');
167
- if (fs.existsSync(libSrcDir)) {
168
- fs.readdirSync(libSrcDir, { withFileTypes: true })
169
- .filter(entry => entry.isFile())
170
- .forEach(entry => {
171
- const label = `lib/${entry.name}`;
172
- atomicCopyFile(
173
- path.join(libSrcDir, entry.name),
174
- path.join(destDir, label),
175
- dryRun,
176
- noBackup,
177
- label
178
- );
179
- });
180
- }
173
+ // Non-hook modules (lib/*, adapter-common.sh, deploy-manifest.sh, install.sh)
174
+ // come from MODULE_FILES rather than a directory enumeration.
175
+ //
176
+ // REQ-DEPLOY-002: enumerating `hooks/lib/` meant the updater installed whatever
177
+ // happened to be in that directory — including files no manifest declared — and
178
+ // left adapter-common.sh / deploy-manifest.sh / install.sh uninstalled entirely.
179
+ // Enumerating the manifest instead makes the install plan readable.
180
+ const { MODULE_FILES } = require('./deploy-manifest.js');
181
+ MODULE_FILES.forEach(rel => {
182
+ atomicCopyFile(
183
+ path.join(hooksSrcDir, rel),
184
+ path.join(destDir, rel),
185
+ dryRun,
186
+ noBackup,
187
+ rel
188
+ );
189
+ });
181
190
  }
182
191
 
183
192
  /**
@@ -3,7 +3,7 @@
3
3
  **Generated:** 2026-11-04
4
4
  **Commit:** eb2097b0
5
5
  **Branch:** sprint/2026-11-03-02
6
- **Version:** 0.37.3.0
6
+ **Version:** 0.38.1.0
7
7
 
8
8
  ## OVERVIEW
9
9
  Mock layering policy enforcement — Gate M3 of pre-push hook. Ensures integration tests use real implementations for internal dependencies, mock external dependencies, and annotate pending mocks with removal plans. Combines project scope scanning, mock decision engine, and per-file validation into a single pipeline.
@@ -3,7 +3,7 @@
3
3
  **Generated:** 2026-11-04
4
4
  **Commit:** eb2097b0
5
5
  **Branch:** sprint/2026-11-03-02
6
- **Version:** 0.37.3.0
6
+ **Version:** 0.38.1.0
7
7
 
8
8
  ## OVERVIEW
9
9
  **Gate M** (incremental mutation testing) + **Gate M2** helpers (test-layer detection used by `src/mock-policy/`). Pre-push quality gate. TypeScript-only; uses Stryker.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@boyingliu01/xp-gate",
3
- "version": "0.37.3",
3
+ "version": "0.38.1",
4
4
  "description": "AI-driven development workflow: 6 quality gates + Delphi review + Sprint Flow",
5
5
  "bin": {
6
6
  "xp-gate": "bin/xp-gate.js"
@@ -29,6 +29,7 @@
29
29
  "gate-10.sh",
30
30
  "gate-12-file-hygiene.sh",
31
31
  "gate-13-compiler-strictness.sh",
32
+ "gate-registry.sh",
32
33
  "sprint-gate.sh"
33
34
  ],
34
35
  "dsh": {
@@ -59,6 +60,7 @@
59
60
  "version": "0.20.0",
60
61
  "license-check": "node scripts/check-mattpocock-license.cjs",
61
62
  "prepack": "node scripts/check-mattpocock-license.cjs && node scripts/sync-package-content.js",
63
+ "prepare": "node scripts/generate-mirrors.cjs --quiet",
62
64
  "test": "echo \"Run tests\" && exit 0"
63
65
  },
64
66
  "keywords": [
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "xp-gate",
3
- "version": "0.37.3",
3
+ "version": "0.38.1",
4
4
  "displayName": "XP-Gate",
5
5
  "description": "Extreme Programming quality gates + AI workflow skills for Claude Code. Includes 12 pre-commit gates (Gate 0-11), 8 pre-push gates, Sprint Flow (6 phases), and Delphi multi-expert review (>=90% consensus).",
6
6
  "author": {
@@ -3,7 +3,7 @@
3
3
  **Generated:** 2026-11-04
4
4
  **Commit:** eb2097b0
5
5
  **Branch:** sprint/2026-11-03-02
6
- **Version:** 0.37.3.0
6
+ **Version:** 0.38.1.0
7
7
 
8
8
  ## OVERVIEW
9
9
  Delphi Consensus Review — multi-round anonymous expert review (≥90% threshold, exactly 3 experts with distinct executable model IDs). Supports design, requirements, and code-walkthrough modes.
@@ -3,7 +3,7 @@
3
3
  **Generated:** 2026-11-04
4
4
  **Commit:** eb2097b0
5
5
  **Branch:** sprint/2026-11-03-02
6
- **Version:** 0.37.3.0
6
+ **Version:** 0.38.1.0
7
7
 
8
8
  ## OVERVIEW
9
9
  **6-phase** development pipeline (v2.0 compact redesign, Issue #290): PREP → DESIGN → BUILD → VERIFY → SHIP → CLOSE. Phase 3/6 BUILD default build mode is **ralph-loop** (REQ-level iteration, 40-67% token savings vs parallel). HARD-GATE between DESIGN (2/6) and BUILD (3/6): design must pass Delphi review (≥90% consensus) before any coding.
@@ -3,7 +3,7 @@
3
3
  **Generated:** 2026-11-04
4
4
  **Commit:** eb2097b0
5
5
  **Branch:** sprint/2026-11-03-02
6
- **Version:** 0.37.3.0
6
+ **Version:** 0.38.1.0
7
7
 
8
8
  ## OVERVIEW
9
9
  Test-Specification Alignment Engine — two-stage validation ensuring tests accurately reflect requirements and design specs.
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@boyingliu01/dsh-plugin-xp-gate",
3
- "version": "0.37.3",
3
+ "version": "0.38.1",
4
4
  "description": "XP-Gate deterministic quality gates + AI workflow skills as a DeepSeek Harness (DSH) native plugin: gate-check / gate-principles / gate-arch tools + 12 SKILL.md skills",
5
5
  "type": "module",
6
6
  "main": "./lib/index.js",
@@ -3,7 +3,7 @@
3
3
  **Generated:** 2026-11-04
4
4
  **Commit:** eb2097b0
5
5
  **Branch:** sprint/2026-11-03-02
6
- **Version:** 0.37.3.0
6
+ **Version:** 0.38.1.0
7
7
 
8
8
  ## OVERVIEW
9
9
  Delphi Consensus Review — multi-round anonymous expert review (≥90% threshold, exactly 3 experts with distinct executable model IDs). Supports design, requirements, and code-walkthrough modes.
@@ -3,7 +3,7 @@
3
3
  **Generated:** 2026-11-04
4
4
  **Commit:** eb2097b0
5
5
  **Branch:** sprint/2026-11-03-02
6
- **Version:** 0.37.3.0
6
+ **Version:** 0.38.1.0
7
7
 
8
8
  ## OVERVIEW
9
9
  **6-phase** development pipeline (v2.0 compact redesign, Issue #290): PREP → DESIGN → BUILD → VERIFY → SHIP → CLOSE. Phase 3/6 BUILD default build mode is **ralph-loop** (REQ-level iteration, 40-67% token savings vs parallel). HARD-GATE between DESIGN (2/6) and BUILD (3/6): design must pass Delphi review (≥90% consensus) before any coding.
@@ -3,7 +3,7 @@
3
3
  **Generated:** 2026-11-04
4
4
  **Commit:** eb2097b0
5
5
  **Branch:** sprint/2026-11-03-02
6
- **Version:** 0.37.3.0
6
+ **Version:** 0.38.1.0
7
7
 
8
8
  ## OVERVIEW
9
9
  Test-Specification Alignment Engine — two-stage validation ensuring tests accurately reflect requirements and design specs.
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@boyingliu01/opencode-plugin",
3
- "version": "0.37.3",
3
+ "version": "0.38.1",
4
4
  "type": "module",
5
5
  "main": "index.ts",
6
6
  "description": "XP-Gate quality gates + AI workflow skills for OpenCode",
@@ -3,7 +3,7 @@
3
3
  **Generated:** 2026-11-04
4
4
  **Commit:** eb2097b0
5
5
  **Branch:** sprint/2026-11-03-02
6
- **Version:** 0.37.3.0
6
+ **Version:** 0.38.1.0
7
7
 
8
8
  ## OVERVIEW
9
9
  Delphi Consensus Review — multi-round anonymous expert review (≥90% threshold, exactly 3 experts with distinct executable model IDs). Supports design, requirements, and code-walkthrough modes.
@@ -3,7 +3,7 @@
3
3
  **Generated:** 2026-11-04
4
4
  **Commit:** eb2097b0
5
5
  **Branch:** sprint/2026-11-03-02
6
- **Version:** 0.37.3.0
6
+ **Version:** 0.38.1.0
7
7
 
8
8
  ## OVERVIEW
9
9
  **6-phase** development pipeline (v2.0 compact redesign, Issue #290): PREP → DESIGN → BUILD → VERIFY → SHIP → CLOSE. Phase 3/6 BUILD default build mode is **ralph-loop** (REQ-level iteration, 40-67% token savings vs parallel). HARD-GATE between DESIGN (2/6) and BUILD (3/6): design must pass Delphi review (≥90% consensus) before any coding.
@@ -3,7 +3,7 @@
3
3
  **Generated:** 2026-11-04
4
4
  **Commit:** eb2097b0
5
5
  **Branch:** sprint/2026-11-03-02
6
- **Version:** 0.37.3.0
6
+ **Version:** 0.38.1.0
7
7
 
8
8
  ## OVERVIEW
9
9
  Test-Specification Alignment Engine — two-stage validation ensuring tests accurately reflect requirements and design specs.
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "xp-gate",
3
- "version": "0.37.3",
3
+ "version": "0.38.1",
4
4
  "displayName": "XP-Gate",
5
5
  "description": "Extreme Programming quality gates + AI workflow skills for Qoder. Includes 12 pre-commit gates (Gate 0-11), 8 pre-push gates, Sprint Flow (6 phases), and Delphi multi-expert review (>=90% consensus).",
6
6
  "author": {
@@ -3,7 +3,7 @@
3
3
  **Generated:** 2026-11-04
4
4
  **Commit:** eb2097b0
5
5
  **Branch:** sprint/2026-11-03-02
6
- **Version:** 0.37.3.0
6
+ **Version:** 0.38.1.0
7
7
 
8
8
  ## OVERVIEW
9
9
  Delphi Consensus Review — multi-round anonymous expert review (≥90% threshold, exactly 3 experts with distinct executable model IDs). Supports design, requirements, and code-walkthrough modes.
@@ -3,7 +3,7 @@
3
3
  **Generated:** 2026-11-04
4
4
  **Commit:** eb2097b0
5
5
  **Branch:** sprint/2026-11-03-02
6
- **Version:** 0.37.3.0
6
+ **Version:** 0.38.1.0
7
7
 
8
8
  ## OVERVIEW
9
9
  **6-phase** development pipeline (v2.0 compact redesign, Issue #290): PREP → DESIGN → BUILD → VERIFY → SHIP → CLOSE. Phase 3/6 BUILD default build mode is **ralph-loop** (REQ-level iteration, 40-67% token savings vs parallel). HARD-GATE between DESIGN (2/6) and BUILD (3/6): design must pass Delphi review (≥90% consensus) before any coding.
@@ -3,7 +3,7 @@
3
3
  **Generated:** 2026-11-04
4
4
  **Commit:** eb2097b0
5
5
  **Branch:** sprint/2026-11-03-02
6
- **Version:** 0.37.3.0
6
+ **Version:** 0.38.1.0
7
7
 
8
8
  ## OVERVIEW
9
9
  Test-Specification Alignment Engine — two-stage validation ensuring tests accurately reflect requirements and design specs.
@@ -3,7 +3,7 @@
3
3
  **Generated:** 2026-11-04
4
4
  **Commit:** eb2097b0
5
5
  **Branch:** sprint/2026-11-03-02
6
- **Version:** 0.37.3.0
6
+ **Version:** 0.38.1.0
7
7
 
8
8
  ## OVERVIEW
9
9
  Clean Code & SOLID principles checker — **Gate 4** of pre-commit. 14 rules × 9 language adapters, SARIF 2.1.0 output. Houses the **Boy Scout Rule** enforcement engine (Gate 6) and warning-baseline storage.
@@ -23,7 +23,8 @@ describe('analyzer.ts - Rule Orchestration Engine', () => {
23
23
  ]),
24
24
  extractClasses: vi.fn().mockReturnValue([]),
25
25
  extractExports: vi.fn().mockReturnValue([]),
26
- countLines: vi.fn().mockReturnValue(100)
26
+ countLines: vi.fn().mockReturnValue(100),
27
+ getDuplication: vi.fn().mockReturnValue({ percentage: 0, blocks: [] })
27
28
  };
28
29
 
29
30
  // Mock rule that detects violations
@@ -134,6 +134,7 @@ function adapterReportingLines(totalLines: number): Adapter {
134
134
  extractClasses: () => [],
135
135
  extractExports: () => [],
136
136
  countLines: () => totalLines,
137
+ getDuplication: () => ({ percentage: 0, blocks: [] }),
137
138
  };
138
139
  }
139
140
 
@@ -92,6 +92,7 @@ describe('types.ts - Core Interfaces', () => {
92
92
  extractClasses: () => [],
93
93
  extractExports: () => [],
94
94
  countLines: () => 0,
95
+ getDuplication: () => ({ percentage: 0, blocks: [] }),
95
96
  };
96
97
 
97
98
  expect(adapter.detectLanguage).toBeDefined();
@@ -1,6 +1,8 @@
1
1
  import { readFileSync } from 'fs';
2
2
  import { extname } from 'path';
3
- import { Adapter } from '../types';
3
+ import { Adapter, DuplicationReport } from '../types';
4
+ import { measureDuplication } from './duplication';
5
+
4
6
 
5
7
  export abstract class BaseAdapter implements Adapter {
6
8
  protected readonly filePath: string;
@@ -59,6 +61,17 @@ export abstract class BaseAdapter implements Adapter {
59
61
  return this.fileContent.split('\n').length;
60
62
  }
61
63
 
64
+ /**
65
+ * Measure intra-file duplication.
66
+ *
67
+ * Delegates to ./duplication so the algorithm stays testable on its own and
68
+ * BaseAdapter does not grow into a subsystem. See that module for why the
69
+ * measurement is line-level and which lines are excluded.
70
+ */
71
+ getDuplication(): DuplicationReport {
72
+ return measureDuplication(this.fileContent);
73
+ }
74
+
62
75
  protected readFileContent(filePath: string): string {
63
76
  try {
64
77
  return readFileSync(filePath, 'utf-8');
@@ -0,0 +1,134 @@
1
+ /**
2
+ * Intra-file duplication measurement.
3
+ *
4
+ * Lives outside `BaseAdapter` on purpose: the measurement is a pure function of
5
+ * the file content, and putting it in the base class pushed that class past the
6
+ * method-count limit (`clean-code.god-class` / `solid.srp`, both correctly fired
7
+ * at 19 methods vs a maximum of 15). A base class should not grow a subsystem.
8
+ */
9
+ import { DuplicationBlock, DuplicationReport } from '../types';
10
+
11
+ /**
12
+ * Consecutive significant lines that must match before they count as a repeated
13
+ * region. Three is the smallest run that is still evidence of copying rather
14
+ * than coincidence: at two, every `try {` / `} catch {` pair qualifies.
15
+ */
16
+ export const DUPLICATION_WINDOW = 3;
17
+
18
+ /** A duplicated region longer than this is truncated in the report snippet. */
19
+ const SNIPPET_LIMIT = 120;
20
+
21
+ /** Collapse whitespace so indentation differences do not hide a copy. */
22
+ function normaliseLine(line: string): string {
23
+ return line.trim().replace(/\s+/g, ' ');
24
+ }
25
+
26
+ /**
27
+ * Indexes of lines that carry code.
28
+ *
29
+ * Blank lines, lone braces and comment-only lines are excluded. A file of 40
30
+ * short functions shares `}` and `return x;` with itself constantly; counting
31
+ * those reports near-100% duplication for perfectly ordinary code, which is how
32
+ * a duplication gate gets switched off.
33
+ */
34
+ function significantLineIndexes(lines: string[]): number[] {
35
+ const indexes: number[] = [];
36
+ for (let i = 0; i < lines.length; i++) {
37
+ const text = normaliseLine(lines[i]);
38
+ if (text.length === 0) continue;
39
+ if (text === '{' || text === '}' || text === '};' || text === '});') continue;
40
+ if (text.startsWith('//') || text.startsWith('/*') || text.startsWith('*')) continue;
41
+ indexes.push(i);
42
+ }
43
+ return indexes;
44
+ }
45
+
46
+ /** Group duplicated line indexes into contiguous, human-readable regions. */
47
+ function buildBlocks(lines: string[], duplicated: Set<number>): DuplicationBlock[] {
48
+ const sorted = [...duplicated].sort((a, b) => a - b);
49
+ const blocks: DuplicationBlock[] = [];
50
+ let runStart = sorted[0];
51
+ let runEnd = sorted[0];
52
+
53
+ const flush = (): void => {
54
+ const snippet =
55
+ lines
56
+ .slice(runStart, runEnd + 1)
57
+ .map((line) => normaliseLine(line))
58
+ .find((line) => line.length > 0) ?? '';
59
+ blocks.push({
60
+ startLine: runStart + 1,
61
+ endLine: runEnd + 1,
62
+ // The window count that covered this run start; see measureDuplication.
63
+ occurrences: 1,
64
+ snippet: snippet.slice(0, SNIPPET_LIMIT),
65
+ });
66
+ };
67
+
68
+ for (const lineIndex of sorted.slice(1)) {
69
+ if (lineIndex === runEnd + 1) {
70
+ runEnd = lineIndex;
71
+ continue;
72
+ }
73
+ flush();
74
+ runStart = lineIndex;
75
+ runEnd = lineIndex;
76
+ }
77
+ flush();
78
+
79
+ // Longest region first: that is the one worth extracting.
80
+ return blocks.sort((a, b) => b.endLine - b.startLine - (a.endLine - a.startLine));
81
+ }
82
+
83
+ /**
84
+ * Measure how much of the file repeats itself.
85
+ *
86
+ * A line-level window fingerprint, not a token clone: runs of
87
+ * `DUPLICATION_WINDOW` significant lines are keyed into a map, and every line
88
+ * inside a window seen more than once is marked duplicated. Overlapping marks
89
+ * form one region, so a large copied block is not counted twice.
90
+ *
91
+ * Line-level rather than token-level because this runs per file inside Gate 4
92
+ * and must stay cheap (measured 0.6–2.9 ms/file). Cross-file token-level clones
93
+ * remain Gate 2's job — jscpd already does that, and duplicating it here would
94
+ * make two gates disagree about the same word.
95
+ */
96
+ export function measureDuplication(content: string): DuplicationReport {
97
+ const lines = content.split('\n');
98
+ const significant = significantLineIndexes(lines);
99
+ const total = significant.length;
100
+
101
+ if (total < DUPLICATION_WINDOW * 2) {
102
+ return { percentage: 0, blocks: [] };
103
+ }
104
+
105
+ const duplicated = new Set<number>();
106
+ const seen = new Set<string>();
107
+ let repeatCount = 0;
108
+
109
+ for (let i = 0; i + DUPLICATION_WINDOW <= significant.length; i++) {
110
+ const window = significant.slice(i, i + DUPLICATION_WINDOW);
111
+ const fingerprint = window.map((lineIndex) => normaliseLine(lines[lineIndex])).join('\u0000');
112
+ if (!seen.has(fingerprint)) {
113
+ seen.add(fingerprint);
114
+ continue;
115
+ }
116
+ repeatCount++;
117
+ for (const lineIndex of window) duplicated.add(lineIndex);
118
+ }
119
+
120
+ if (duplicated.size === 0) {
121
+ return { percentage: 0, blocks: [] };
122
+ }
123
+
124
+ const blocks = buildBlocks(lines, duplicated);
125
+ // TODO(REQ-PRINCIPLES-DUP): `occurrences` is only meaningful for blocks[0].
126
+ // Every other block keeps the builder's default of 1, and the count below is
127
+ // the file-wide repeat total, not a per-block count. Harmless today because
128
+ // the rule reads only `percentage` and no CLI surfaces blocks -- but a future
129
+ // consumer would read wrong data silently, so this is a trap, not a feature.
130
+ // Correct fix is to count occurrences per fingerprint group inside
131
+ // buildBlocks (code-walkthrough R2, A4/F5).
132
+ if (blocks.length > 0) blocks[0].occurrences = repeatCount + 1;
133
+ return { percentage: (duplicated.size / total) * 100, blocks };
134
+ }
@@ -8,7 +8,8 @@ const mockAdapter = {
8
8
  extractFunctions: () => [],
9
9
  extractClasses: () => [],
10
10
  extractExports: () => [],
11
- countLines: (_fileName: string) => 10 // Default to small file
11
+ countLines: (_fileName: string) => 10, // Default to small file
12
+ getDuplication: () => ({ percentage: 0, blocks: [] })
12
13
  };
13
14
 
14
15
  describe('largeFileRule', () => {
@@ -1,6 +1,56 @@
1
- import { Rule, Violation, Severity } from '../../types';
1
+ import { Rule, Violation, Severity, DuplicationReport } from '../../types';
2
2
  import { getActiveConfig } from '../../config';
3
3
 
4
+ /**
5
+ * Resolve the duplication percentage to judge.
6
+ *
7
+ * `getDuplication()` on the adapter is the supported source. `duplicationPercentage`
8
+ * is a DEPRECATED compatibility shim, kept only so an integrator that already
9
+ * measures duplication elsewhere (a token-level clone detector, a cached report)
10
+ * is not broken by this rebuild.
11
+ *
12
+ * Precedence: explicit `duplicationPercentage` wins, then `getDuplication()`.
13
+ * The explicit field wins because it is a deliberate caller override -- a value
14
+ * computed out-of-band must not be silently overruled by the adapter's own
15
+ * cheaper estimate.
16
+ *
17
+ * DEPRECATION (code-walkthrough R2, A1/F2/F-3): callers should move to
18
+ * `Adapter.getDuplication()`. The shim is the one remaining path that can still
19
+ * satisfy the rule without the typed contract -- it is read structurally, so a
20
+ * third-party adapter need not implement the REQUIRED interface member. That
21
+ * gap is deliberate and bounded: the shim is being retired, not extended. When
22
+ * it is removed, every consumer must implement `getDuplication`.
23
+ *
24
+ * If neither is available the result says so explicitly; the caller turns that
25
+ * into a visible diagnostic. Silently judging nothing is the defect this rule
26
+ * was rebuilt to remove, not an acceptable fallback.
27
+ */
28
+ function resolveDuplicationPercentage(
29
+ adapter: unknown,
30
+ ): { percentage: number } | { unavailable: string } {
31
+ const supplier = adapter as {
32
+ duplicationPercentage?: number;
33
+ getDuplication?: () => DuplicationReport;
34
+ };
35
+
36
+ if (typeof supplier.duplicationPercentage === 'number') {
37
+ return { percentage: supplier.duplicationPercentage };
38
+ }
39
+ if (typeof supplier.getDuplication === 'function') {
40
+ return { percentage: supplier.getDuplication().percentage };
41
+ }
42
+ return {
43
+ unavailable:
44
+ 'adapter supplies neither duplicationPercentage nor getDuplication()',
45
+ };
46
+ }
47
+
48
+ /** Format a percentage so a small non-zero value never prints as "0%". */
49
+ function formatPercentage(value: number): string {
50
+ if (value > 0 && value < 1) return value.toFixed(2);
51
+ return String(Math.round(value * 10) / 10);
52
+ }
53
+
4
54
  export const codeDuplicationRule: Rule = {
5
55
  id: 'clean-code.code-duplication',
6
56
  name: 'Code Duplication Rule',
@@ -10,20 +60,36 @@ export const codeDuplicationRule: Rule = {
10
60
  const violations: Violation[] = [];
11
61
  // Read the ACTIVE config per invocation; a module-load snapshot was #457.
12
62
  const settings = getActiveConfig().rules['clean-code']['code-duplication'];
13
-
14
- const typedAdapter = adapter as { duplicationPercentage?: number };
15
- const duplicationPercentage = typedAdapter.duplicationPercentage;
16
-
17
- if (duplicationPercentage && duplicationPercentage > (settings.threshold ?? 0)) {
63
+
64
+ const resolved = resolveDuplicationPercentage(adapter);
65
+
66
+ // A capability gap is reported, never swallowed. Returning [] here is
67
+ // exactly how this rule spent its whole life looking enabled while firing
68
+ // nothing (REQ-PRINCIPLES-DUP): silence and "measured clean" were
69
+ // indistinguishable. `info`, not `warning`, because a third-party adapter
70
+ // can trigger it and it must not block a commit — but it IS visible, and
71
+ // `xp-gate gate-coverage` can therefore surface it.
72
+ if ('unavailable' in resolved) {
18
73
  violations.push({
19
74
  file,
20
75
  line: 1,
21
76
  ruleId: 'clean-code.code-duplication',
22
- message: `Code duplication detected: ${duplicationPercentage}% (threshold: ${settings.threshold}%). Consider refactoring duplicated code.`,
77
+ message: `Duplication not measured: ${resolved.unavailable}. The rule cannot judge this file, so it is NOT reporting it clean — implement getDuplication() on the adapter.`,
78
+ severity: 'info',
79
+ });
80
+ return violations;
81
+ }
82
+
83
+ if (resolved.percentage > (settings.threshold ?? 0)) {
84
+ violations.push({
85
+ file,
86
+ line: 1,
87
+ ruleId: 'clean-code.code-duplication',
88
+ message: `Code duplication detected: ${formatPercentage(resolved.percentage)}% (threshold: ${settings.threshold}%). Consider refactoring duplicated code.`,
23
89
  severity: (settings.severity as Severity) ?? 'warning'
24
90
  });
25
91
  }
26
-
92
+
27
93
  return violations;
28
94
  }
29
- };
95
+ };
@@ -32,6 +32,29 @@ export interface Violation {
32
32
  severity: Severity;
33
33
  }
34
34
 
35
+ /**
36
+ * Duplication measured for one file.
37
+ *
38
+ * `blocks` exists so a caller can explain the percentage rather than only assert
39
+ * it; the rule reports the number, the CLI can point at the lines.
40
+ */
41
+ export interface DuplicationReport {
42
+ /** Share of the file's significant lines that repeat elsewhere in the file. */
43
+ percentage: number;
44
+ /** Each repeated region, longest first. */
45
+ blocks: DuplicationBlock[];
46
+ }
47
+
48
+ export interface DuplicationBlock {
49
+ /** 1-based inclusive line range of the first occurrence. */
50
+ startLine: number;
51
+ endLine: number;
52
+ /** How many further occurrences of this block exist in the same file. */
53
+ occurrences: number;
54
+ /** Normalised text shared by the occurrences, for human diagnosis. */
55
+ snippet: string;
56
+ }
57
+
35
58
  export interface Adapter {
36
59
  detectLanguage: () => string;
37
60
  parseAST: () => unknown;
@@ -39,4 +62,20 @@ export interface Adapter {
39
62
  extractClasses: () => unknown[];
40
63
  extractExports: () => unknown[];
41
64
  countLines: () => number;
65
+ /**
66
+ * Measure intra-file duplication.
67
+ *
68
+ * REQUIRED, deliberately. The first version of this member was optional, and
69
+ * that re-created the very defect it was added to fix: an optional member plus
70
+ * a `undefined`-means-no-violation branch is still "a rule configured
71
+ * `enabled: true` that silently never fires" — the failure just moved from
72
+ * "the field was never declared" to "the adapter forgot to implement it".
73
+ * A silent capability gap is the same lie as a silent field gap.
74
+ *
75
+ * Every in-repo adapter extends `BaseAdapter`, which implements this, so
76
+ * requiring it costs nothing here. A third-party adapter written against the
77
+ * old interface gets a compile error — which is the point: it must decide,
78
+ * not default into silence.
79
+ */
80
+ getDuplication: () => DuplicationReport;
42
81
  }