@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
package/hooks/pre-push CHANGED
@@ -986,19 +986,39 @@ else
986
986
 
987
987
  for test_file in $ALL_PUSHED_TEST_FILES; do
988
988
  if [ -f "$test_file" ]; then
989
- # Count mock keyword references (precise patterns only)
990
- # Use grep -o piped to wc -l for reliable single-number output (grep -c can emit
991
- # multi-line output with filenames under some grep versions, causing bash arithmetic
992
- # syntax errors). grep -o extracts each match on its own line, wc -l counts them.
989
+ # Count mock keyword references (precise patterns only).
990
+ #
991
+ # This used to be `for kw in ...; do grep -o "$kw" | wc -l; done`: 20
992
+ # keywords x (grep + wc) = 40 process creations, for a scan of ONE file.
993
+ # Process creation is the dominant cost in this hook (a single pre-push
994
+ # run executes ~359 commands), so that loop alone measured ~5.5 s of the
995
+ # ~25 s pre-push on the reference 100-line fixture.
996
+ #
997
+ # The file is read ONCE and the same per-keyword arithmetic runs with bash
998
+ # builtins, which forks nothing. This is deliberately NOT a single
999
+ # `grep -oE 'a|b|c'`: that form counts each keyword's matches once, while
1000
+ # the loop double-counts overlaps ("vi.mockResolvedValue" matches both
1001
+ # `vi.mock` and `mockResolvedValue`). Switching to one alternation would
1002
+ # silently LOWER the density and weaken Gate M2. Equivalence with the old
1003
+ # loop was verified on 40 real test files plus overlap/edge fixtures (0
1004
+ # mismatches).
1005
+ local _mock_content _mock_kw _mock_rest _mock_c
1006
+ _mock_content="$(cat "$test_file" 2>/dev/null)" || _mock_content=""
993
1007
  MOCK_COUNT=0
994
- for kw in 'jest\.mock' 'vi\.mock' 'jest\.spyOn' 'vi\.spyOn' 'jest\.fn' 'vi\.fn' \
995
- 'mockResolvedValue' 'mockRejectedValue' 'mockReturnValue' 'mockImplementation' \
996
- 'createMock' 'mockReset' 'mockClear' 'mockRestore' 'MagicMock' 'unittest\.mock' \
997
- '\.patch(' 'gomock' 'mockgen' '.EXPECT()'; do
998
- c=$(grep -o "$kw" "$test_file" 2>/dev/null | wc -l || true)
999
- c=${c//[^0-9]/}
1000
- c=${c:-0}
1001
- MOCK_COUNT=$((MOCK_COUNT + c))
1008
+ for _mock_kw in "jest.mock" "vi.mock" "jest.spyOn" "vi.spyOn" "jest.fn" "vi.fn" \
1009
+ "mockResolvedValue" "mockRejectedValue" "mockReturnValue" \
1010
+ "mockImplementation" "createMock" "mockReset" "mockClear" \
1011
+ "mockRestore" "MagicMock" "unittest.mock" ".patch(" "gomock" \
1012
+ "mockgen" ".EXPECT()"; do
1013
+ _mock_rest="$_mock_content"
1014
+ _mock_c=0
1015
+ while :; do
1016
+ case "$_mock_rest" in
1017
+ *"$_mock_kw"*) _mock_c=$((_mock_c + 1)); _mock_rest="${_mock_rest#*"$_mock_kw"}" ;;
1018
+ *) break ;;
1019
+ esac
1020
+ done
1021
+ MOCK_COUNT=$((MOCK_COUNT + _mock_c))
1002
1022
  done
1003
1023
 
1004
1024
  # Count total non-empty, non-comment lines for density denominator
@@ -1328,7 +1348,20 @@ EXPECTED_COMMIT=$(git rev-parse HEAD)
1328
1348
 
1329
1349
  # Validate the complete evidence contract without interpolating JSON into shell.
1330
1350
  HOOK_DIR=$(CDPATH= cd -- "$(dirname -- "$0")" && pwd)
1331
- MW_VALIDATOR="$HOOK_DIR/lib/validate-code-walkthrough.cjs"
1351
+ # #739: under Git Bash $HOOK_DIR is a POSIX path (/d/projects/...). `test -f`
1352
+ # accepts it because MSYS resolves that form itself, but node.exe does not: it
1353
+ # reads a leading "/d" as drive-relative and reports
1354
+ # "Cannot find module 'D:\d\projects\...'". So the guard below PASSED and the
1355
+ # consumer crashed, which is why this surfaced as a Node stack trace instead of
1356
+ # the intended "Gate MW validator is missing" message. cygpath is the documented
1357
+ # conversion; where it is absent (plain POSIX, no MSYS) the path is already
1358
+ # native and is left untouched.
1359
+ if command -v cygpath >/dev/null 2>&1; then
1360
+ HOOK_DIR_FOR_NODE=$(cygpath -w "$HOOK_DIR")
1361
+ else
1362
+ HOOK_DIR_FOR_NODE="$HOOK_DIR"
1363
+ fi
1364
+ MW_VALIDATOR="$HOOK_DIR_FOR_NODE/lib/validate-code-walkthrough.cjs"
1332
1365
  if [ ! -f "$MW_VALIDATOR" ]; then
1333
1366
  echo ""
1334
1367
  echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
@@ -4,7 +4,7 @@
4
4
  * @intent Expose the four AGENTS.md runtime anti-patterns (blocking job_output,
5
5
  * literal sleep, CI polling loops, serial tool calls) as machine-checkable
6
6
  * numbers instead of a prose rule that nobody measures.
7
- * @covers AC-712-01
7
+ * @covers AC-712-01, AC-712-06
8
8
  * @covers AC-712-02
9
9
  * @covers AC-712-03
10
10
  * @covers AC-712-04
@@ -58,6 +58,15 @@ let sandbox;
58
58
 
59
59
  beforeEach(() => {
60
60
  sandbox = fs.mkdtempSync(path.join(os.tmpdir(), 'xpgate-arch-'));
61
+ // A `.git` marker is load-bearing for RUNTIME, not just for findProjectRoot.
62
+ // archlint locates its own project root by walking up from the scan target.
63
+ // With no marker anywhere up the chain it settles on the user's home
64
+ // directory and walks every one of its trees -- measured on this machine:
65
+ // 97,423 ms for an EMPTY temp dir versus 208 ms once a `.git` exists here,
66
+ // and `--no-git` does not help (git-history churn is not the cost). Without
67
+ // this marker the file's ~20 real-archlint calls paid ~98 s each, which is
68
+ // where arch.test.js's 2,146 s came from.
69
+ fs.mkdirSync(path.join(sandbox, '.git'), { recursive: true });
61
70
  });
62
71
 
63
72
  afterEach(() => {
@@ -1,5 +1,5 @@
1
1
  /**
2
- * @test audit CLI runs at all
2
+ * @test REQ-673
3
3
  * @intent The four `xp-gate audit` subcommands used to require() a .ts file, which
4
4
  * Node cannot do, so every one of them died. This pins that they execute,
5
5
  * that --check still FAILS on a real anomaly (so "it runs" is not mistaken
@@ -1,5 +1,5 @@
1
1
  /**
2
- * @test REQ-599
2
+ * @test REQ-599, REQ-541
3
3
  * @intent `check-alignment` printed only its status and counters when it blocked:
4
4
  *
5
5
  * Status: BLOCKED
@@ -17,6 +17,16 @@
17
17
  * that a non-PASS verdict carrying NO reason is reported as the producer
18
18
  * bug it is rather than printed as an empty list.
19
19
  * @covers AC-599-09
20
+ *
21
+ * Also covers one of REQ-541's acceptance criteria (the dsh-016 family): a
22
+ * non-PASS verdict must print every reason, a PASS must not print a reasons
23
+ * block, and a FAIL carrying no reasons must be named a producer defect. The
24
+ * criterion id is deliberately not written here in its full form: the
25
+ * ac-reference-guard matcher only understands two-segment ids, so a
26
+ * three-segment reference gets truncated to a prefix the spec does not contain
27
+ * and is reported as new debt. Widening that matcher changes how all 95 frozen
28
+ * baseline files are read (147 new + 39 ghost entries), which is a separate
29
+ * change. The REQ-541 tag above keeps the requirement link machine-readable.
20
30
  */
21
31
  import { describe, it, expect } from 'vitest';
22
32
  import { readFileSync } from 'fs';
@@ -19,7 +19,7 @@
19
19
  * ran and silent about the five that did not. `verdict: PARTIAL` in the
20
20
  * hook's own report exists for the same reason; the CLI had no such
21
21
  * notion. This is report §5 phase-0 action 0.2.
22
- * @covers AC-568-01, AC-568-02, AC-568-03
22
+ * @covers AC-568-01, AC-568-02, AC-568-03, AC-568-04
23
23
  */
24
24
  const gateRunner = require('../gate-runner.js');
25
25
  const { checkAllGates, formatGateTally } = require('../check.js');
@@ -0,0 +1,135 @@
1
+ /**
2
+ * @test REQ-gate-identity GATE_CLI_TOOLS 的门禁编号必须与 gate-registry.sh 一致
3
+ * @intent `xp-gate doctor` 用 GATE_CLI_TOOLS 里的 gates[] 告诉用户"这个工具服务哪道门禁"。
4
+ * 编号漂移会直接把用户指到错的门禁上——#717 曾经因为同样的漂移,把 C# SAST 的修复
5
+ * 写进了 gate-9.sh(那是 Build Integrity,不是 SAST),修了却从未被执行。
6
+ * 权威来源是 githooks/gate-registry.sh,本测试从它读行并逐条对照,而不是硬编码期望值:
7
+ * 硬编码只能证明"今天两边都写 10",读 registry 才能证明"两边不会各自漂走"。
8
+ * @covers AC-GATE-IDENTITY-01, AC-GATE-IDENTITY-02
9
+ */
10
+ const fs = require('node:fs');
11
+ const path = require('node:path');
12
+
13
+ const REPO_ROOT = path.resolve(__dirname, '..', '..', '..', '..');
14
+ const REGISTRY = path.join(REPO_ROOT, 'githooks', 'gate-registry.sh');
15
+
16
+ /** Gate 9 is Build Integrity; Gate 10 is SAST. Named so the assertion reads as a claim, not a literal. */
17
+ const BUILD_INTEGRITY_GATE = 9;
18
+
19
+ /**
20
+ * Read gate-registry.sh, naming the registry in any failure.
21
+ *
22
+ * A missing or unreadable registry means the FIXTURE broke, not the code under
23
+ * test. Left unguarded it would surface as a raw ENOENT from inside a parser and
24
+ * read like "detect-deps is wrong" — the misleading diagnosis this whole file
25
+ * exists to prevent. Resolution is relative to the repo, so a moved file fails
26
+ * with a path instead of a stack trace.
27
+ *
28
+ * @returns {string} registry file contents
29
+ */
30
+ function readRegistryOrFail() {
31
+ try {
32
+ return fs.readFileSync(REGISTRY, 'utf8');
33
+ } catch (err) {
34
+ throw new Error(`fixture: cannot read gate registry at ${REGISTRY}: ${err.message}`);
35
+ }
36
+ }
37
+
38
+ /**
39
+ * Parse the `"name|N|file|sourced"` rows out of gate-registry.sh.
40
+ *
41
+ * @returns {Map<string, number>} gate name -> gate number
42
+ */
43
+ function readRegistryGateNumbers() {
44
+ const text = readRegistryOrFail();
45
+ const numbers = new Map();
46
+ const row = /^\s*"([a-z-]+)\|(\d+)\|/gm;
47
+ let m;
48
+ while ((m = row.exec(text)) !== null) numbers.set(m[1], Number(m[2]));
49
+ return numbers;
50
+ }
51
+
52
+ /** The human title registry maps to each name, so a tool's label can be matched without guessing. */
53
+ function readGateTitles() {
54
+ const text = readRegistryOrFail();
55
+ const titles = new Map();
56
+ const row = /^\s*([a-z-]+)\)\s+echo "([^"]+)"/gm;
57
+ let m;
58
+ while ((m = row.exec(text)) !== null) titles.set(m[1], m[2]);
59
+ return titles;
60
+ }
61
+
62
+ /** Every `gates: ['Gate <n> (<label>)', ...]` entry, flattened to {tool, gateNumber, label}. */
63
+ function readToolGateRefs() {
64
+ const { GATE_CLI_TOOLS } = require('../detect-deps');
65
+ const refs = [];
66
+ for (const entry of GATE_CLI_TOOLS) {
67
+ for (const label of entry.gates || []) {
68
+ const m = /^Gate\s+(\d+)\s+\(([^)]+)\)/.exec(label);
69
+ if (m) refs.push({ tool: entry.tool, gateNumber: Number(m[1]), label: m[2] });
70
+ }
71
+ }
72
+ return refs;
73
+ }
74
+
75
+ describe('GATE_CLI_TOOLS gate identity — AC-GATE-IDENTITY-01', () => {
76
+ it('registry itself parses (guards the fixture, not the code under test)', () => {
77
+ const numbers = readRegistryGateNumbers();
78
+ expect(numbers.size).toBeGreaterThanOrEqual(10);
79
+ expect(numbers.get('sast')).toBe(10);
80
+ expect(numbers.get('build-integrity')).toBe(BUILD_INTEGRITY_GATE);
81
+ });
82
+
83
+ it('semgrep is attributed to the SAST gate, not Build Integrity', () => {
84
+ const refs = readToolGateRefs().filter((r) => r.tool === 'semgrep');
85
+ expect(refs.length).toBeGreaterThan(0);
86
+
87
+ const sastNumber = readRegistryGateNumbers().get('sast');
88
+ for (const ref of refs) expect(ref.gateNumber).toBe(sastNumber);
89
+ });
90
+ });
91
+
92
+ describe('GATE_CLI_TOOLS gate identity — AC-GATE-IDENTITY-02', () => {
93
+ it('no tool label names a gate the number does not resolve to', () => {
94
+ const numbers = readRegistryGateNumbers();
95
+ const titles = readGateTitles();
96
+
97
+ // A label is a hand-written gloss, not the canonical title, so equality would be
98
+ // too strict and would fire on legitimate synonyms (Gate 4's label says
99
+ // "Principles via npx tsx" while its title is "Clean Code + SOLID"). What must
100
+ // never happen is a label naming a DIFFERENT gate than the number resolves to —
101
+ // "SAST" filed under the number that means Build Integrity.
102
+ //
103
+ // Detection: every word in a label must be accounted for — it appears in the
104
+ // registry title, or it is a mechanism word. A label saying SAST while the title
105
+ // says Build Integrity leaves "sast" unexplained and fails. The whitelist holds
106
+ // mechanism words, not gate names, so a new gate needs no edit here to be covered.
107
+ const MECHANISM_WORDS = new Set(['via', 'npx', 'tsx', 'docker', 'and', 'the']);
108
+
109
+ const mismatches = [];
110
+ for (const ref of readToolGateRefs()) {
111
+ const name = [...numbers.entries()].find(([, n]) => n === ref.gateNumber)?.[0];
112
+ if (!name) continue;
113
+ // Compare against BOTH the registry key and its human title. The key is the
114
+ // canonical slug ("principles", "sast"), the title is prose ("Clean Code +
115
+ // SOLID", "SAST Security"); a label may legitimately use either. Matching
116
+ // only one of them makes the test fire on naming style instead of on the
117
+ // defect it exists to catch.
118
+ const known = `${name} ${String(titles.get(name) || '')}`.toLowerCase();
119
+ if (!known.trim()) continue;
120
+
121
+ const unexplained = ref.label
122
+ .toLowerCase()
123
+ .split(/[\s/()—]+/)
124
+ .filter(Boolean)
125
+ .filter((word) => !MECHANISM_WORDS.has(word))
126
+ .filter((word) => !known.includes(word));
127
+
128
+ if (unexplained.length > 0) {
129
+ mismatches.push({ tool: ref.tool, gateNumber: ref.gateNumber, registryTitle: titles.get(name), unexplained });
130
+ }
131
+ }
132
+
133
+ expect(mismatches).toEqual([]);
134
+ });
135
+ });
@@ -1,8 +1,9 @@
1
1
  /**
2
- * @test detect-deps
2
+ * @test REQ-424
3
3
  * @intent Verify checkDeps() correctly detects missing/present/outdated dependencies across platforms,
4
4
  * detectPlatform() identifies the correct AI agent platform,
5
5
  * and autoInstallDeps() handles install scenarios
6
+ * @covers AC-424-01, AC-424-02, AC-424-03, AC-424-04
6
7
  */
7
8
  const fs = require('fs');
8
9
  const path = require('path');
@@ -169,7 +169,13 @@ describeWin('doctor PATH staleness (#469, Windows-only)', () => {
169
169
  // a fresh one PASSes — both are legal, a missing check is not.
170
170
  expect(['PASS', 'WARN']).toContain(checks[0].status);
171
171
  expect(checks[0].name).toBe('PATH freshness');
172
- });
172
+ // This case shells out to `reg query` AND probes for bash -- both multi-
173
+ // hundred-millisecond system calls that stretch past vitest's 5s default
174
+ // when the full suite runs in parallel on Windows. It timed out by load,
175
+ // not by hanging: it passes in ~2.8s in isolation. Raising the bound keeps
176
+ // every assertion strict while removing a false red from the pre-commit
177
+ // full-suite path (that suite is what blocks the commit).
178
+ }, 30000);
173
179
 
174
180
  it('AC-469-03: stale registry entries WARN and mention --refresh-env', async () => {
175
181
  const { diagnosePathStaleness } = mod();
@@ -0,0 +1,169 @@
1
+ /**
2
+ * @test REQ-726
3
+ * @intent doctor 必须能诊断架构工具的安装状态。难点是 Java/Kotlin 的 ArchUnit/Konsist
4
+ * 是构建依赖而非 CLI —— 用 checkCmd 永远探不到,会误报「未安装」。
5
+ * 另外每种语言只认自己的坐标,否则 Kotlin 声明 Konsist 会让 Java 误判已装。
6
+ * @covers AC-726-01 AC-726-02 AC-726-03 AC-726-04 AC-726-05 AC-726-06 AC-726-07
7
+ * AC-726-08 AC-726-09
8
+ */
9
+ import { describe, it, expect } from 'vitest';
10
+ import { mkdtempSync, mkdirSync, writeFileSync, rmSync } from 'fs';
11
+ import { tmpdir } from 'os';
12
+ import { join } from 'path';
13
+ import {
14
+ LANGUAGE_REGISTRY,
15
+ getArchitectureTools,
16
+ detectBuildFileDependency,
17
+ } from '../language-tools.js';
18
+
19
+ const dirs = [];
20
+
21
+ /**
22
+ * Create a throwaway project directory populated with `files`.
23
+ *
24
+ * Fixture I/O is wrapped so a failure names the file it was writing: a bare
25
+ * ENOENT from mkdirSync tells the next reader nothing about which fixture broke.
26
+ */
27
+ function projectWith(files) {
28
+ const dir = mkdtempSync(join(tmpdir(), 'xp-gate-arch-tools-'));
29
+ dirs.push(dir);
30
+ for (const [relPath, content] of Object.entries(files)) {
31
+ const full = join(dir, relPath);
32
+ try {
33
+ mkdirSync(join(full, '..'), { recursive: true });
34
+ writeFileSync(full, content, 'utf-8');
35
+ } catch (error) {
36
+ throw new Error(`failed to write fixture ${relPath}: ${error.message}`);
37
+ }
38
+ }
39
+ return dir;
40
+ }
41
+
42
+ /** Clean every temp project this file created. */
43
+ function cleanup() {
44
+ while (dirs.length > 0) {
45
+ const dir = dirs.pop();
46
+ if (dir) rmSync(dir, { recursive: true, force: true });
47
+ }
48
+ }
49
+
50
+ const MAVEN_ARCHUNIT = `<project><dependencies><dependency>
51
+ <groupId>com.tngtech.archunit</groupId>
52
+ <artifactId>archunit-junit5</artifactId>
53
+ </dependency></dependencies></project>`;
54
+
55
+ const GRADLE_KONSIST = `dependencies { testImplementation("com.lemonappdev:konsist:0.13.0") }`;
56
+ const CATALOG_ARCHUNIT = `[libraries]
57
+ archunit = { module = "com.tngtech.archunit:archunit-junit5", version = "1.2.1" }`;
58
+
59
+ describe('AC-726-01/05 — 架构工具在注册表中可见', () => {
60
+ it('每个支持的语言都暴露架构工具条目', () => {
61
+ const arch = getArchitectureTools();
62
+ expect(Object.keys(arch).sort()).toEqual(['go', 'java', 'kotlin', 'python', 'typescript']);
63
+ for (const tools of Object.values(arch)) {
64
+ expect(tools.length).toBeGreaterThan(0);
65
+ }
66
+ });
67
+
68
+ it('每条架构工具都有 name / gates / 安装提示或构建依赖标记', () => {
69
+ for (const tools of Object.values(getArchitectureTools())) {
70
+ for (const tool of tools) {
71
+ expect(typeof tool.name).toBe('string');
72
+ expect(tool.gates.length).toBeGreaterThan(0);
73
+ // Either it is a CLI with per-platform install commands, or it is a
74
+ // build-file dependency -- there is no third shape.
75
+ const hasInstall = tool.install && typeof tool.install === 'object';
76
+ const isBuildDependency = tool.detectBy === 'build-file';
77
+ expect(hasInstall || isBuildDependency).toBe(true);
78
+ }
79
+ }
80
+ });
81
+ });
82
+
83
+ describe('AC-726-08 — 架构工具必须 optional,缺失不改变退出码语义', () => {
84
+ it('所有架构工具都是 optional', () => {
85
+ for (const tools of Object.values(getArchitectureTools())) {
86
+ for (const tool of tools) {
87
+ expect(tool.optional, `${tool.name} must be optional`).toBe(true);
88
+ }
89
+ }
90
+ });
91
+ });
92
+
93
+ describe('AC-726-04 — 不影响既有工具条目', () => {
94
+ it('既有的 mvn / gradle / eslint 条目仍在且形态未变', () => {
95
+ expect(LANGUAGE_REGISTRY.java.tools.some((t) => t.name === 'mvn')).toBe(true);
96
+ expect(LANGUAGE_REGISTRY.java.tools.some((t) => t.name === 'gradle')).toBe(true);
97
+ const eslint = LANGUAGE_REGISTRY.typescript.tools.find((t) => t.name === 'eslint');
98
+ expect(eslint).toBeDefined();
99
+ // Pre-existing CLI tools carry no detectBy, so they keep the default path.
100
+ expect(eslint.detectBy).toBeUndefined();
101
+ });
102
+ });
103
+
104
+ describe('AC-726-03 — 构建依赖检测(ArchUnit / Konsist)', () => {
105
+ it('Maven pom.xml 声明 ArchUnit -> 已安装', () => {
106
+ const dir = projectWith({ 'pom.xml': MAVEN_ARCHUNIT });
107
+ const result = detectBuildFileDependency('java', dir);
108
+ expect(result.available).toBe(true);
109
+ cleanup();
110
+ });
111
+
112
+ it('Gradle 声明 Konsist -> kotlin 已安装', () => {
113
+ const dir = projectWith({ 'build.gradle.kts': GRADLE_KONSIST });
114
+ const result = detectBuildFileDependency('kotlin', dir);
115
+ expect(result.available).toBe(true);
116
+ cleanup();
117
+ });
118
+
119
+ it('没有任何构建文件 -> 未安装(不误报为已装)', () => {
120
+ const dir = projectWith({ 'README.md': '# nothing here' });
121
+ expect(detectBuildFileDependency('java', dir).available).toBe(false);
122
+ cleanup();
123
+ });
124
+
125
+ it('AC-726-06: 坐标只在 gradle/libs.versions.toml 声明时也识别为已安装', () => {
126
+ const dir = projectWith({ 'gradle/libs.versions.toml': CATALOG_ARCHUNIT });
127
+ expect(detectBuildFileDependency('java', dir).available).toBe(true);
128
+ cleanup();
129
+ });
130
+
131
+ // Cross-language isolation: declaring Konsist does NOT mean ArchUnit is
132
+ // present. Without this split, a Kotlin project's build file would turn the
133
+ // Java row green and doctor would stop reporting the real gap.
134
+ it('AC-726-07: Kotlin 项目只声明 Konsist 时,Java 的 archunit 仍报未安装', () => {
135
+ const dir = projectWith({ 'build.gradle.kts': GRADLE_KONSIST });
136
+ expect(detectBuildFileDependency('kotlin', dir).available).toBe(true);
137
+ expect(detectBuildFileDependency('java', dir).available).toBe(false);
138
+ cleanup();
139
+ });
140
+
141
+ it('AC-726-07b: Java 项目只声明 ArchUnit 时,Kotlin 的 konsist 仍报未安装', () => {
142
+ const dir = projectWith({ 'pom.xml': MAVEN_ARCHUNIT });
143
+ expect(detectBuildFileDependency('java', dir).available).toBe(true);
144
+ expect(detectBuildFileDependency('kotlin', dir).available).toBe(false);
145
+ cleanup();
146
+ });
147
+
148
+ // AC-726-09: submodules are not scanned one by one -- the root pom plus the
149
+ // version catalog is the whole search space.
150
+ it('AC-726-09: 仅在子模块 pom.xml 声明时不被识别(只扫根构建文件)', () => {
151
+ const dir = projectWith({ 'core/pom.xml': MAVEN_ARCHUNIT });
152
+ expect(detectBuildFileDependency('java', dir).available).toBe(false);
153
+ cleanup();
154
+ });
155
+ });
156
+
157
+ describe('AC-726-02 — CLI 型工具的安装提示与注册表完全一致', () => {
158
+ it('每个 CLI 架构工具在三大平台都有非空安装命令', () => {
159
+ for (const tools of Object.values(getArchitectureTools())) {
160
+ for (const tool of tools) {
161
+ if (tool.detectBy === 'build-file') continue;
162
+ for (const platform of ['darwin', 'linux', 'win32']) {
163
+ expect(typeof tool.install[platform], `${tool.name}.${platform}`).toBe('string');
164
+ expect(tool.install[platform].length).toBeGreaterThan(0);
165
+ }
166
+ }
167
+ }
168
+ });
169
+ });
@@ -520,7 +520,7 @@ describe('doctor delphi #725 multi-platform skill parity', () => {
520
520
  /**
521
521
  * @test REQ-725 Multi-platform skill parity
522
522
  * @intent A second platform whose copy drifted must fail the parity check instead of being invisible
523
- * @covers AC-725-01
523
+ * @covers AC-725-01, AC-721-01, AC-721-02, AC-721-03
524
524
  */
525
525
  it('AC-725-01: a drifted OpenCode copy FAILs parity even though Qoder is clean', async () => {
526
526
  seedAgents();
@@ -54,10 +54,13 @@ function fixture(spec) {
54
54
  // adapter-common.sh (githooks/pre-commit:34) and gate-3.sh (:80) live in it.
55
55
  // Without them the fixture describes a tier the hook never resolves to, and the
56
56
  // comparison silently targets a directory outside the test (#495 Round 3).
57
+ //
58
+ // The anchors go to the GLOBAL tier only. Precedence is project-first
59
+ // (AC-495-23), so anchoring both trees would make the repo tier execute and
60
+ // these global-vs-repo comparisons would have no executed counterpart left.
57
61
  const ANCHOR = '#!/bin/bash\nanchor\n';
58
62
  for (const anchor of ['adapter-common.sh', 'gate-3.sh']) {
59
63
  if (spec[anchor]) continue;
60
- write(join(repoHooks, anchor), ANCHOR);
61
64
  write(join(installedAdapters, anchor), ANCHOR);
62
65
  }
63
66
 
@@ -49,7 +49,10 @@ function tree(overrides = {}) {
49
49
  // Canonical repo source of truth: nested language adapter, flat gate module.
50
50
  write(join(repoHooks, 'adapter-common.sh'), '#!/bin/bash\nshared\n');
51
51
  write(join(repoHooks, 'pre-commit'), '#!/bin/bash\necho repo\n');
52
- write(join(repoHooks, 'adapters', 'iac.sh'), REPO_ADAPTER);
52
+ // The project tree owns adapter-common.sh, so precedence (AC-495-23) makes it
53
+ // the ADAPTER_DIR -- this nested copy is what actually runs unless a test says
54
+ // otherwise, which is why its content is overridable.
55
+ write(join(repoHooks, 'adapters', 'iac.sh'), overrides.projectNestedIac || REPO_ADAPTER);
53
56
  write(join(repoHooks, 'gate-4.sh'), '#!/bin/bash\ngate_a\ngate_b\n');
54
57
 
55
58
  // Installed global tier: the installer's nested copy is current...
@@ -94,28 +97,39 @@ function checkOf(result, name) {
94
97
  }
95
98
 
96
99
  describe('doctor executed surface (#495 Round 3)', () => {
97
- it('AC-495-14: the executed copy is the flat global one the hook resolves first, so its staleness is a FAIL', () => {
100
+ it('AC-495-14: this repo carries its own githooks/, so the PROJECT copy is executed and a stale global flat copy is only residue', () => {
101
+ // Precedence is project-first (AC-495-23): the global install is the DEFAULT
102
+ // for repos with no githooks/ of their own, not an override of one. This tree
103
+ // has adapter-common.sh in the project tier, so it supplies ADAPTER_DIR and
104
+ // the global flat copy is no longer what runs.
98
105
  const t = tree({ globalFlatIac: STALE_FLAT });
99
106
  const result = drift(t);
100
- const check = checkOf(result, 'Module drift: iac.sh');
101
- expect(check, 'a stale copy the hook executes must FAIL').toBeDefined();
102
- expect(check.status).toBe('FAIL');
103
- expect(result.issues).toBe(1);
107
+ expect(
108
+ checkOf(result, 'Module drift: iac.sh'),
109
+ 'with the project tier winning, the stale global flat copy must not read as executed',
110
+ ).toBeUndefined();
111
+ const shadowed = result.checks.find((c) => /Non-executed copy: iac\.sh/.test(c.name));
112
+ expect(shadowed, 'the shadowed global copy must still be surfaced').toBeDefined();
113
+ expect(shadowed.status).not.toBe('FAIL');
104
114
  });
105
115
 
106
- it('AC-495-15: with a global install present, a flat copy in the project githooks/ does NOT execute and is reported as residue, not as drift', () => {
116
+ it('AC-495-15: with the project tier winning, a flat copy in the project githooks/ DOES execute and is judged as drift', () => {
117
+ // Corrected premise. This test used to assert that a flat project copy never
118
+ // executes, on the reading that the hook only looks for
119
+ // $PROJECT_GITHOOKS/adapters/<lang>.sh there. That is not what the hook does:
120
+ // HOOK_ADAPTER_TIERS starts with 'adapter_flat|ADAPTER_DIR|{name}.sh', and
121
+ // ADAPTER_DIR is now allowed to BE the project tier (AC-495-23), so the flat
122
+ // path is $PROJECT_GITHOOKS/<name>.sh -- the project root. Driving the hook's
123
+ // own _hook_resolve over this fixture returns exactly that file.
124
+ //
125
+ // So the flat project copy is the executed one, and a stale version of it is
126
+ // real drift: a FAIL the developer must fix, not residue to be ignored.
107
127
  const t = tree({ projectFlatIac: undefined });
108
128
  const result = drift(t);
109
- const residue = result.checks.find((c) => /Non-executed copy: iac\.sh/.test(c.name));
110
- expect(residue, 'the project-tier flat copy must still be surfaced').toBeDefined();
111
- // The hook consults $PROJECT_GITHOOKS/adapters/<lang>.sh only (pre-commit:67-69),
112
- // never a flat project copy, so claiming it "executes" would repeat the R1-2 defect.
113
- expect(residue.status).not.toBe('FAIL');
114
- expect(result.issues, 'a copy nothing executes cannot be an unrepairable FAIL').toBe(0);
115
- // Actionable: the offending absolute path, and the manual remedy (#500 is still open).
116
- expect(residue.detail).toContain(t.projectFlatIac);
117
- expect(residue.detail, 'residue must name itself as not executed').toMatch(/not executed|does not execute/i);
118
- expect(residue.detail, 'residue must say how to get rid of it').toMatch(/gitignore|residue|remove/i);
129
+ const executed = result.checks.find((c) => /iac\.sh/.test(c.name) && !/Non-executed/.test(c.name));
130
+ expect(executed, 'the executed project-tier flat copy must be diagnosed').toBeDefined();
131
+ expect(executed.status).toBe('FAIL');
132
+ expect(result.issues).toBeGreaterThanOrEqual(1);
119
133
  });
120
134
 
121
135
  it('AC-495-16: the same project-tier flat copy IS executed once ADAPTER_DIR resolves to the project tier, and then it FAILs', () => {
@@ -169,24 +183,31 @@ describe('doctor executed surface (#495 Round 3)', () => {
169
183
  });
170
184
 
171
185
  it('AC-495-18: every FAIL the resolution can produce, syncModulesFromRepo can clear', () => {
186
+ // With the project tier owning ADAPTER_DIR, the executed copy is the project's
187
+ // flat iac.sh (AC-495-15). A stale one there is drift against the repo's
188
+ // nested source, and the repair must reach that same tier -- otherwise the
189
+ // FAIL is permanent, which is exactly what this AC forbids.
172
190
  const { syncModulesFromRepo, diagnoseModuleDrift } = require('../doctor');
173
- const t = tree({ globalFlatIac: SUBSET_FLAT, projectFlatIac: null });
191
+ const t = tree({ globalFlatIac: undefined, projectFlatIac: SUBSET_FLAT });
174
192
  const ctx = ctxFor(t);
175
- expect(diagnoseModuleDrift(ctx).issues).toBe(1);
193
+ expect(diagnoseModuleDrift(ctx).issues).toBeGreaterThanOrEqual(1);
176
194
 
177
195
  const synced = syncModulesFromRepo(ctx);
178
196
  expect(synced.synced).toContain('iac.sh');
179
- expect(readFileSync(join(t.globalAdapters, 'iac.sh'), 'utf8')).toContain('fixed_count_guard');
197
+ expect(readFileSync(t.projectFlatIac, 'utf8')).toContain('fixed_count_guard');
180
198
  expect(diagnoseModuleDrift(ctx).issues).toBe(0);
181
199
  });
182
200
 
183
201
  it('AC-495-18b: the sync never deletes or rewrites non-executed residue on its own initiative', () => {
202
+ // A flat project copy IS executed now (AC-495-15), so residue has to be a
203
+ // copy in a tier that the resolution does not pick: the global flat one,
204
+ // shadowed by the project tier that owns ADAPTER_DIR.
184
205
  const { syncModulesFromRepo } = require('../doctor');
185
- const t = tree({ globalFlatIac: SUBSET_FLAT });
186
- const before = readFileSync(t.projectFlatIac, 'utf8');
206
+ const t = tree({ globalFlatIac: SUBSET_FLAT, projectFlatIac: null });
207
+ const before = readFileSync(join(t.globalAdapters, 'iac.sh'), 'utf8');
187
208
  const synced = syncModulesFromRepo(ctxFor(t));
188
- expect(synced.synced).toContain('iac.sh');
189
- expect(readFileSync(t.projectFlatIac, 'utf8')).toBe(before);
209
+ expect(synced.synced).not.toContain('iac.sh');
210
+ expect(readFileSync(join(t.globalAdapters, 'iac.sh'), 'utf8')).toBe(before);
190
211
  });
191
212
 
192
213
  it('AC-495-19: an unreadable destination is refused, not overwritten', () => {