@boyingliu01/xp-gate 0.37.0 → 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 (55) hide show
  1. package/adapters/typescript.sh +11 -1
  2. package/gate-10.sh +66 -0
  3. package/gate-13-compiler-strictness.sh +81 -1
  4. package/gate-6-layers.sh +375 -0
  5. package/hooks/gate-10.sh +66 -0
  6. package/hooks/gate-13-compiler-strictness.sh +81 -1
  7. package/hooks/gate-6-layers.sh +375 -0
  8. package/hooks/gate-registry.sh +2 -2
  9. package/hooks/hook-module-resolution.sh +1 -1
  10. package/hooks/lib/layer-baseline.cjs +88 -0
  11. package/hooks/lib/typecheck.sh +28 -5
  12. package/hooks/pre-commit +96 -11
  13. package/lib/__tests__/detect-deps-gate-identity.test.js +135 -0
  14. package/lib/__tests__/doctor-drift-round2.test.js +4 -1
  15. package/lib/__tests__/doctor-executed-surface.test.js +45 -24
  16. package/lib/__tests__/doctor-module-drift.test.js +13 -7
  17. package/lib/__tests__/doctor-module-resolution-parity.test.js +74 -2
  18. package/lib/__tests__/doctor.test.js +17 -0
  19. package/lib/__tests__/gate-runner-tsx-invocation.test.js +149 -0
  20. package/lib/__tests__/gate-runner.test.js +23 -7
  21. package/lib/__tests__/phase-transition.test.js +19 -1
  22. package/lib/__tests__/sprint-status-rework.test.js +32 -12
  23. package/lib/detect-deps.js +7 -1
  24. package/lib/doctor.js +81 -17
  25. package/lib/gate-runner.js +101 -7
  26. package/lib/hook-module-resolution.js +18 -6
  27. package/lib/layer-baseline.cjs +88 -0
  28. package/lib/mattpocock-license-verdict.json +1 -1
  29. package/mock-policy/AGENTS.md +1 -1
  30. package/mutation/AGENTS.md +1 -1
  31. package/package.json +2 -1
  32. package/plugins/claude-code/.claude-plugin/plugin.json +1 -1
  33. package/plugins/claude-code/skills/delphi-review/AGENTS.md +1 -1
  34. package/plugins/claude-code/skills/sprint-flow/AGENTS.md +1 -1
  35. package/plugins/claude-code/skills/test-specification-alignment/AGENTS.md +1 -1
  36. package/plugins/dsh/package.json +1 -1
  37. package/plugins/dsh/skills/delphi-review/AGENTS.md +1 -1
  38. package/plugins/dsh/skills/sprint-flow/AGENTS.md +1 -1
  39. package/plugins/dsh/skills/test-specification-alignment/AGENTS.md +1 -1
  40. package/plugins/opencode/package.json +1 -1
  41. package/plugins/opencode/skills/delphi-review/AGENTS.md +1 -1
  42. package/plugins/opencode/skills/sprint-flow/AGENTS.md +1 -1
  43. package/plugins/opencode/skills/test-specification-alignment/AGENTS.md +1 -1
  44. package/plugins/qoder/plugin.json +1 -1
  45. package/plugins/qoder/skills/delphi-review/AGENTS.md +1 -1
  46. package/plugins/qoder/skills/sprint-flow/AGENTS.md +1 -1
  47. package/plugins/qoder/skills/test-specification-alignment/AGENTS.md +1 -1
  48. package/principles/AGENTS.md +1 -1
  49. package/principles/adapters/csharp.ts +73 -42
  50. package/principles/adapters/java.ts +9 -5
  51. package/principles/adapters/typescript.ts +130 -45
  52. package/principles/index.ts +30 -14
  53. package/skills/delphi-review/AGENTS.md +1 -1
  54. package/skills/sprint-flow/AGENTS.md +1 -1
  55. package/skills/test-specification-alignment/AGENTS.md +1 -1
package/hooks/pre-commit CHANGED
@@ -229,13 +229,19 @@ fi
229
229
  PROJECT_GITHOOKS="$(run_without_git_context git rev-parse --show-toplevel 2>/dev/null)/githooks"
230
230
  GATES_DIR="$SCRIPT_DIR/gates"
231
231
 
232
- if [ -f "$GLOBAL_ADAPTER_DIR/adapter-common.sh" ]; then
233
- ADAPTER_DIR="$GLOBAL_ADAPTER_DIR"
234
- elif [ -f "$PROJECT_GITHOOKS/adapter-common.sh" ]; then
235
- ADAPTER_DIR="$PROJECT_GITHOOKS"
236
- else
237
- ADAPTER_DIR="$SCRIPT_DIR"
238
- fi
232
+ # ADAPTER_DIR decides which tree every later lookup searches, so its ORDER comes
233
+ # from HOOK_ADAPTER_DIR_TIERS (generated from lib/hook-module-resolution.js) and
234
+ # never from a cascade typed here. This block used to be a hand-written
235
+ # `if global ... elif project ...`, which meant the generated table was loaded and
236
+ # then ignored: flipping the spec to project-first changed nothing at runtime
237
+ # while the data file and doctor both already reported the new order.
238
+ #
239
+ # _hook_resolve, not _hook_resolve_dir: the ADAPTER table's third field is the
240
+ # probe FILENAME ('adapter-common.sh'), so resolving it as a module template is
241
+ # what yields "<tier_dir>/adapter-common.sh". _hook_resolve_dir treats that field
242
+ # as a directory suffix and would build "<tier_dir>adapter-common.sh/...".
243
+ ADAPTER_DIR="$(_hook_resolve 'adapter-common' HOOK_ADAPTER_DIR_TIERS)" || ADAPTER_DIR="$SCRIPT_DIR"
244
+ ADAPTER_DIR="${ADAPTER_DIR%/adapter-common.sh}"
239
245
  source "$ADAPTER_DIR/adapter-common.sh" 2>/dev/null || {
240
246
  echo "Error: Cannot source adapter-common.sh from $ADAPTER_DIR"
241
247
  echo "Run: xp-gate init (per-project) or xp-gate setup-global (all projects)"
@@ -4347,10 +4353,71 @@ else
4347
4353
  # return "supported" no matter what. File presence is the only honest input.
4348
4354
  GATE_6_LAYERS_UNCHECKED=0
4349
4355
  if [ -f "$PROJECT_ROOT/architecture.yaml" ] || [ -f "$PROJECT_ROOT/.architecturerc" ]; then
4356
+ # The declaration is now read by a checker of our own, so the warning
4357
+ # below is no longer "nothing looked at this" — it is "archlint did not".
4358
+ # The verdict on layer boundaries comes from gate-6-layers.sh; this flag
4359
+ # only records that archlint's generic-smell pass measured no layers.
4350
4360
  GATE_6_LAYERS_UNCHECKED=1
4351
- echo " ⚠️ [WARN:LAYERS_UNCHECKED] 分层规则未校验:architecture.yaml 声明的层边界当前不被任何检测器消费"
4352
- echo " (实测 @archlinter/cli 0.16.0 的 layer_violation 启用后亦无输出;见 #686)"
4353
- echo " 本次仅校验通用架构坏味道(循环依赖 / 上帝类 / 死代码)。"
4361
+ fi
4362
+
4363
+ # Layer-boundary enforcement (#686 / #691 / #728).
4364
+ # This runs in addition to archlint, not instead of it: archlint checks
4365
+ # generic smells (cycles, god modules, dead code) and its layer_violation
4366
+ # detector is a measured no-op, so the dependency direction has to be
4367
+ # checked directly. The checker always builds the whole-repo import graph —
4368
+ # a layer violation is an edge between two directories, so an incremental
4369
+ # per-directory scan structurally cannot see one.
4370
+ LAYER_CHECKER=""
4371
+ if [ -f "$GATE_DIR/gate-6-layers.sh" ]; then
4372
+ LAYER_CHECKER="$GATE_DIR/gate-6-layers.sh"
4373
+ elif [ -f "$(git rev-parse --show-toplevel 2>/dev/null)/githooks/gate-6-layers.sh" ]; then
4374
+ LAYER_CHECKER="$(git rev-parse --show-toplevel)/githooks/gate-6-layers.sh"
4375
+ fi
4376
+ if [ -n "$LAYER_CHECKER" ]; then
4377
+ LAYER_OUT=$(cd "$PROJECT_ROOT" && bash "$LAYER_CHECKER" 2>&1)
4378
+ LAYER_RC=$?
4379
+ printf '%s\n' "$LAYER_OUT" | sed 's/^/ /'
4380
+ case "$LAYER_RC" in
4381
+ 0)
4382
+ GATE_6_LAYER_STATUS="PASS"
4383
+ ;;
4384
+ 1)
4385
+ GATE_6_LAYER_STATUS="FAIL"
4386
+ GATE_6_STATUS="FAIL"
4387
+ ;;
4388
+ 2)
4389
+ # Config present but unusable: fail closed. Reporting PASS here is the
4390
+ # exact defect #686 documented, one level deeper.
4391
+ GATE_6_LAYER_STATUS="BLOCK"
4392
+ GATE_6_STATUS="FAIL"
4393
+ ;;
4394
+ 3)
4395
+ # WARN (no layer config, or only baselined violations).
4396
+ GATE_6_LAYER_STATUS="WARN"
4397
+ ;;
4398
+ *)
4399
+ # Any other exit means the checker itself did not complete: 126/127
4400
+ # (not executable / not found), 137 (killed), or a bash error. Mapping
4401
+ # those to WARN would let a crashed checker pass as "not checked",
4402
+ # which is #686's defect one level deeper — the gate would look like it
4403
+ # covered layers while nothing ran. Fail closed.
4404
+ GATE_6_LAYER_STATUS="BLOCK"
4405
+ GATE_6_STATUS="FAIL"
4406
+ GATE_6_LAYER_REASON="layer_checker_crashed_rc_${LAYER_RC}"
4407
+ GATE_6_LAYER_CRASHED=1
4408
+ ;;
4409
+ esac
4410
+ GATE_6_LAYER_REASON=${GATE_6_LAYER_REASON:-$(printf '%s\n' "$LAYER_OUT" | sed -n 's/^ *reason: *//p' | head -1)}
4411
+ else
4412
+ # The checker is missing, so the dimension is unmeasured — say so rather
4413
+ # than letting the gate look like it covered layers.
4414
+ GATE_6_LAYER_STATUS="WARN"
4415
+ GATE_6_LAYER_REASON="layer_checker_missing"
4416
+ echo " ⚠️ [WARN:LAYER_CHECKER_MISSING] gate-6-layers.sh not found — layer boundaries NOT checked."
4417
+ fi
4418
+ if [ "${GATE_6_LAYER_CRASHED:-0}" = "1" ]; then
4419
+ echo " ❌ [BLOCK:LAYER_CHECKER_CRASHED] gate-6-layers.sh exited $LAYER_RC without a verdict."
4420
+ echo " A checker that did not finish has not checked anything — fail closed."
4354
4421
  fi
4355
4422
  # #537: per-language reason bookkeeping. Gate 3/4 are single-language gates
4356
4423
  # and get away with one scalar reason; Gate 6 loops, so a scalar would lose
@@ -5302,7 +5369,14 @@ fi
5302
5369
  # first place.
5303
5370
  # ============================================================================
5304
5371
  MIRROR_STAGED=$(git diff --cached --name-only --diff-filter=ACMR 2>/dev/null || true)
5305
- if [ -n "$MIRROR_STAGED" ] && printf '%s\n' "$MIRROR_STAGED" | grep -qE '^(githooks/|plugins/[^/]+/src/)'; then
5372
+ # `src/npm-package/` is in this filter because a mirror-only edit is the
5373
+ # dangerous direction, not the harmless one. Keying off the canonical paths
5374
+ # alone meant staging just the mirror skipped the whole block, so a fix written
5375
+ # into the published copy could be committed while its source stayed wrong --
5376
+ # v0.27.3 shipped exactly that (#542). The reverse mapping below resolves each
5377
+ # staged mirror back to its canonical file and compares the pair either way.
5378
+ if [ -n "$MIRROR_STAGED" ] && printf '%s
5379
+ ' "$MIRROR_STAGED" | grep -qE '^(githooks/|plugins/[^/]+/src/|src/npm-package/(adapters|hooks|principles|build-integrity)/)'; then
5306
5380
  # Reuse PROJECT_ROOT: `git rev-parse` costs ~90ms per fork on Windows and this
5307
5381
  # gate must not add two of them to every commit (#640).
5308
5382
  MIRROR_REPO_ROOT="${PROJECT_ROOT:-}"
@@ -5334,6 +5408,15 @@ if [ -n "$MIRROR_STAGED" ] && printf '%s\n' "$MIRROR_STAGED" | grep -qE '^(githo
5334
5408
  githooks/adapters/*) _mm="src/npm-package/adapters/${_mf#githooks/adapters/}" ;;
5335
5409
  githooks/*) _mm="src/npm-package/hooks/${_mf#githooks/}" ;;
5336
5410
  plugins/*/src/*) _mm=$(printf '%s' "$_mf" | sed 's|^plugins/\([^/]*\)/src/|src/npm-package/plugins/\1/src/|') ;;
5411
+ # Reverse direction: the staged file IS the mirror. Resolve it back to
5412
+ # the canonical file and let the same comparison below decide. Without
5413
+ # this arm the widened filter above matches nothing and the gate stays
5414
+ # blind to a mirror-only edit -- the v0.27.3 shape (#542).
5415
+ src/npm-package/adapters/*) _mf="githooks/adapters/${_mf#src/npm-package/adapters/}"; _mm="src/npm-package/adapters/${_mf#githooks/adapters/}" ;;
5416
+ src/npm-package/hooks/lib/*) _mf="githooks/lib/${_mf#src/npm-package/hooks/lib/}"; _mm="src/npm-package/hooks/lib/${_mf#githooks/lib/}" ;;
5417
+ src/npm-package/hooks/*) _mf="githooks/${_mf#src/npm-package/hooks/}"; _mm="src/npm-package/hooks/${_mf#githooks/}" ;;
5418
+ src/npm-package/principles/*) _mf="src/principles/${_mf#src/npm-package/principles/}"; _mm="src/npm-package/principles/${_mf#src/principles/}" ;;
5419
+ src/npm-package/build-integrity/*) _mf="src/build-integrity/${_mf#src/npm-package/build-integrity/}"; _mm="src/npm-package/build-integrity/${_mf#src/build-integrity/}" ;;
5337
5420
  *) continue ;;
5338
5421
  esac
5339
5422
  if [ ! -f "$MIRROR_REPO_ROOT/$_mm" ]; then
@@ -5770,6 +5853,8 @@ generate_quality_report() {
5770
5853
  "status": "${GATE_10_STATUS:-SKIP}",
5771
5854
  "reason": "${GATE_10_REASON:-}",
5772
5855
  "scanned_files": ${GATE_10_SCANNED_FILES:-0},
5856
+ "path": "${GATE_10_SEMGREP_PATH:-direct}",
5857
+ "degraded": ${GATE_10_SASTD_DEGRADED:-0},
5773
5858
  "tool": "semgrep"
5774
5859
  },
5775
5860
  "gate11_sprint_flow": {
@@ -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
+ });
@@ -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', () => {
@@ -18,7 +18,7 @@ import { describe, expect, it } from 'vitest';
18
18
  * Build a repo + global-install pair. `spec` names each module's repo copy and
19
19
  * installed copy; null means "not present on that side".
20
20
  */
21
- function fixture(spec) {
21
+ function fixture(spec, options = {}) {
22
22
  const root = mkdtempSync(join(tmpdir(), 'xp-gate-drift-'));
23
23
  const repoHooks = join(root, 'githooks');
24
24
  const installedHooks = join(root, 'hooks');
@@ -49,15 +49,21 @@ function fixture(spec) {
49
49
  write(join(repoHooks, 'pre-commit'), '#!/bin/bash\necho repo\n');
50
50
  write(join(installedHooks, 'pre-commit'), '#!/bin/bash\necho repo\n');
51
51
 
52
- // Resolution anchors: pre-commit only makes the installed dir the ADAPTER_DIR
53
- // when `adapter-common.sh` is in it (:34), and only reads gate modules from it
54
- // when `gate-3.sh` is (:80). Without both, the fixture describes a tier the hook
55
- // never resolves to, and the comparison silently targets some other directory
56
- // (#495 Round 3 -- the tier list is no longer an assumption).
52
+ // Resolution anchors. Which tier OWNS the anchor decides which tier executes:
53
+ // precedence is project-first (AC-495-23), so writing adapter-common.sh into
54
+ // the repo tree would make the repo tier run and these global-vs-repo drift
55
+ // comparisons would have no executed counterpart to describe.
56
+ //
57
+ // The default here is therefore the GLOBAL-anchored world: a repo that carries
58
+ // faithful copies in githooks/ but has not taken the tier over. Consumers that
59
+ // never run `xp-gate init` are in exactly this shape, and it is what the drift
60
+ // surface is for. Tests that want the project tier to win pass
61
+ // { projectTakesOver: true }.
57
62
  const ANCHOR = '#!/bin/bash\nanchor\n';
63
+ const projectOwnsAnchor = options.projectTakesOver === true;
58
64
  for (const anchor of ['adapter-common.sh', 'gate-3.sh']) {
59
65
  if (spec[anchor]) continue;
60
- write(join(repoHooks, anchor), ANCHOR);
66
+ if (projectOwnsAnchor) write(join(repoHooks, anchor), ANCHOR);
61
67
  write(join(installedAdapters, anchor), ANCHOR);
62
68
  }
63
69
 
@@ -250,11 +250,31 @@ describe('doctor module resolution parity with pre-commit (#495)', () => {
250
250
  // Anti-vacuity for the whole feature: if the hook re-grew a literal cascade,
251
251
  // the single-source-of-truth claim would be false even while scenarios pass.
252
252
  expect(PRE_COMMIT).toContain('hook-module-resolution.sh');
253
- expect(PRE_COMMIT).toContain('HOOK_ADAPTER_TIERS');
254
- expect(PRE_COMMIT).toContain('HOOK_GATE_TIERS');
253
+ // MENTIONING the array is not enough -- this assertion used to stop at
254
+ // `toContain('HOOK_ADAPTER_TIERS')`, which the array's own declaration
255
+ // satisfies. The hook sourced the generated file and then resolved
256
+ // ADAPTER_DIR with a hand-written global-first cascade that never read the
257
+ // array, so the data was dead weight and the spec change had no effect at
258
+ // runtime while this test stayed green. Require an actual consumption.
259
+ //
260
+ // The readers expand the table indirectly (`eval "set -- ${tiers_var}[@]"`,
261
+ // because the same helper serves both tables), so look for the call sites
262
+ // that name each table rather than for a literal `${NAME[@]}`.
263
+ expect(PRE_COMMIT, 'ADAPTER_DIR is never resolved from HOOK_ADAPTER_DIR_TIERS').toMatch(
264
+ /_hook_resolve(?:_dir)?\s+['"][^'"]+['"]\s+HOOK_ADAPTER_DIR_TIERS/,
265
+ );
266
+ expect(PRE_COMMIT, 'GATE_DIR is never resolved from HOOK_GATE_TIERS').toMatch(
267
+ /_hook_resolve(?:_dir)?\s+['"][^'"]+['"]\s+HOOK_GATE_TIERS/,
268
+ );
255
269
  // The old hand-written chains must be gone.
256
270
  expect(PRE_COMMIT).not.toContain('$ADAPTER_DIR/${lang}.sh');
257
271
  expect(PRE_COMMIT).not.toMatch(/if \[ -f "\$ADAPTER_DIR\/gate-3\.sh" \]; then/);
272
+ // And the ADAPTER_DIR cascade specifically must not be re-typed: a literal
273
+ // "global first, then project" if/elif is exactly the order this data
274
+ // replaces.
275
+ expect(PRE_COMMIT, 'ADAPTER_DIR still has a hand-written global-first cascade').not.toMatch(
276
+ /if \[ -f "\$GLOBAL_ADAPTER_DIR\/adapter-common\.sh" \][\s\S]{0,120}ADAPTER_DIR="\$GLOBAL_ADAPTER_DIR"/,
277
+ );
258
278
  // And every tier the JS declares must appear in the emitted shell data.
259
279
  for (const t of RESOLUTION_ORDER) {
260
280
  expect(RESOLUTION_DATA).toContain(`${t.tier_id}|${t.base}|${t.template}`);
@@ -372,6 +392,58 @@ describe('doctor module resolution parity with pre-commit (#495)', () => {
372
392
  }
373
393
  });
374
394
 
395
+ it('AC-495-23: a project install OVERRIDES the global install (project is the higher tier)', () => {
396
+ // The install modes exist so the global copy is a DEFAULT that a project can
397
+ // override: "no per-project customisation -> use the global gate suite; this
398
+ // project has special needs -> its own copy wins". The cascade used to try
399
+ // GLOBAL first, which made a project's githooks/ unreachable whenever the
400
+ // machine had a global install -- so editing the repo's own gate scripts
401
+ // changed nothing, silently.
402
+ const idxGlobal = ADAPTER_DIR_ORDER.findIndex((t) => t.tier_id === 'global');
403
+ const idxProject = ADAPTER_DIR_ORDER.findIndex((t) => t.tier_id === 'project');
404
+ expect(idxProject, 'no project tier in ADAPTER_DIR_ORDER').toBeGreaterThanOrEqual(0);
405
+ expect(idxGlobal, 'no global tier in ADAPTER_DIR_ORDER').toBeGreaterThanOrEqual(0);
406
+ expect(
407
+ idxProject,
408
+ 'project must be consulted BEFORE global, or a per-project gate suite can never take effect',
409
+ ).toBeLessThan(idxGlobal);
410
+
411
+ // And the hook, driven by the generated data, must actually pick the project
412
+ // copy when both trees carry the module.
413
+ const { resolveExecutedModuleDirs, executedModulePath } = require('../doctor');
414
+ const t = fourTierTree({
415
+ 'adapter-common.sh': ['globalFlat', 'projectFlat'],
416
+ 'typescript.sh': ['globalFlat', 'projectNested'],
417
+ 'gate-3.sh': ['globalFlat', 'projectFlat'],
418
+ });
419
+ const dirs = resolveExecutedModuleDirs({
420
+ globalAdapterDir: t.globalAdapters,
421
+ projectGithooks: t.projectGithooks,
422
+ scriptDir: t.scriptDir,
423
+ });
424
+ const hook = hookResolvesAll(blocks, resolverText, t, 'typescript', 'gate-3.sh');
425
+
426
+ expect(
427
+ samePath(hook.adapterDir, t.projectGithooks),
428
+ `ADAPTER_DIR resolved to ${hook.adapterDir}; the project tier must win over global`,
429
+ ).toBe(true);
430
+ expect(samePath(hook.langPath, join(t.projectGithooks, 'adapters', 'typescript.sh'))).toBe(true);
431
+ expect(samePath(executedModulePath('typescript.sh', dirs), hook.langPath)).toBe(true);
432
+ });
433
+
434
+ it('AC-495-24: a project with no githooks/ still uses the global install', () => {
435
+ // The override must not become "the global install stops working": a repo
436
+ // that never ran `xp-gate init` has to keep resolving to the global tree.
437
+ const t = fourTierTree({
438
+ 'adapter-common.sh': ['globalFlat'],
439
+ 'typescript.sh': ['globalFlat'],
440
+ 'gate-3.sh': ['globalFlat'],
441
+ });
442
+ const hook = hookResolvesAll(blocks, resolverText, t, 'typescript', 'gate-3.sh');
443
+ expect(samePath(hook.adapterDir, t.globalAdapters)).toBe(true);
444
+ expect(samePath(hook.langPath, join(t.globalAdapters, 'typescript.sh'))).toBe(true);
445
+ });
446
+
375
447
  it('AC-495-22: a module no tier installs resolves to nothing on both sides', () => {
376
448
  const { resolveExecutedModuleDirs, executedModulePath } = require('../doctor');
377
449
  const t = fourTierTree({
@@ -31,6 +31,7 @@ describe('doctor', () => {
31
31
  let originalDetectDepsTools;
32
32
  let originalExecSync;
33
33
  let originalExec;
34
+ let originalSpawnSync;
34
35
  let logSpy;
35
36
 
36
37
  beforeAll(() => {
@@ -67,6 +68,7 @@ describe('doctor', () => {
67
68
  originalRepoRoot = process.env.XP_GATE_REPO_ROOT;
68
69
  originalExecSync = cp.execSync;
69
70
  originalExec = cp.exec;
71
+ originalSpawnSync = cp.spawnSync;
70
72
  // Unique per-describe + per-test prefixes to avoid parallel collisions.
71
73
  tmpHome = fs.mkdtempSync(path.join(os.tmpdir(), `xpgate-dr-${DESCRIBE_ID}-`));
72
74
  tmpProject = fs.mkdtempSync(path.join(os.tmpdir(), `xpgate-dr-proj-${DESCRIBE_ID}-`));
@@ -91,6 +93,20 @@ describe('doctor', () => {
91
93
  logSpy = vi.spyOn(console, 'log').mockImplementation(() => {});
92
94
  vi.spyOn(console, 'warn').mockImplementation(() => {});
93
95
  vi.spyOn(console, 'error').mockImplementation(() => {});
96
+ // doctor.js destructures `const { execSync, execFileSync, spawnSync } =
97
+ // require('child_process')`, so each reloaded copy captures the function
98
+ // objects that exist at require time. Patching cp.spawnSync AFTER the
99
+ // reload has no effect on it -- that was tried, and the file did not get
100
+ // faster by a single millisecond. The patch therefore goes on the module
101
+ // object here, before the next test's `require('../doctor')` runs.
102
+ //
103
+ // Why it is safe: checkSpawnCapability() exists to warn a user whose sandbox
104
+ // forbids sync spawns, and no case in this file asserts its verdict. Every
105
+ // real git call here is likewise probing an environment the fixtures have
106
+ // deliberately redirected to tmpHome/tmpProject, so "not a git repository"
107
+ // is the honest answer rather than a fabricated one. Measured on this
108
+ // machine, one doctor() call spent 80% of its samples inside spawnSync.
109
+ cp.spawnSync = () => ({ error: null, status: 0, stdout: 'v24.0.0\n', stderr: '' });
94
110
  });
95
111
 
96
112
  afterEach(() => {
@@ -100,6 +116,7 @@ describe('doctor', () => {
100
116
  else process.env.XP_GATE_REPO_ROOT = originalRepoRoot;
101
117
  cp.execSync = originalExecSync;
102
118
  cp.exec = originalExec;
119
+ cp.spawnSync = originalSpawnSync;
103
120
  if (tmpHome && fs.existsSync(tmpHome)) {
104
121
  fs.rmSync(tmpHome, { recursive: true, force: true });
105
122
  }