@boyingliu01/xp-gate 0.37.0 → 0.37.2

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 (60) 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/sprint-flow/references/phase-5-ship.md +6 -2
  36. package/plugins/claude-code/skills/test-specification-alignment/AGENTS.md +1 -1
  37. package/plugins/dsh/package.json +1 -1
  38. package/plugins/dsh/skills/delphi-review/AGENTS.md +1 -1
  39. package/plugins/dsh/skills/sprint-flow/AGENTS.md +1 -1
  40. package/plugins/dsh/skills/sprint-flow/references/phase-5-ship.md +6 -2
  41. package/plugins/dsh/skills/test-specification-alignment/AGENTS.md +1 -1
  42. package/plugins/opencode/package.json +1 -1
  43. package/plugins/opencode/skills/delphi-review/AGENTS.md +1 -1
  44. package/plugins/opencode/skills/sprint-flow/AGENTS.md +1 -1
  45. package/plugins/opencode/skills/sprint-flow/references/phase-5-ship.md +6 -2
  46. package/plugins/opencode/skills/test-specification-alignment/AGENTS.md +1 -1
  47. package/plugins/qoder/plugin.json +1 -1
  48. package/plugins/qoder/skills/delphi-review/AGENTS.md +1 -1
  49. package/plugins/qoder/skills/sprint-flow/AGENTS.md +1 -1
  50. package/plugins/qoder/skills/sprint-flow/references/phase-5-ship.md +6 -2
  51. package/plugins/qoder/skills/test-specification-alignment/AGENTS.md +1 -1
  52. package/principles/AGENTS.md +1 -1
  53. package/principles/adapters/csharp.ts +73 -42
  54. package/principles/adapters/java.ts +9 -5
  55. package/principles/adapters/typescript.ts +130 -45
  56. package/principles/index.ts +30 -14
  57. package/skills/delphi-review/AGENTS.md +1 -1
  58. package/skills/sprint-flow/AGENTS.md +1 -1
  59. package/skills/sprint-flow/references/phase-5-ship.md +6 -2
  60. package/skills/test-specification-alignment/AGENTS.md +1 -1
@@ -0,0 +1,149 @@
1
+ /**
2
+ * @test REQ-ts-gate-startup tsx 直调(#779)
3
+ * @intent 证明 TypeScript 门禁不再经 `npx -y tsx` 启动,而是用当前 node.exe 直接
4
+ * 运行 tsx 的 cli.mjs。`npx -y` 每次都要重新解析包位置,实测 4.5-5.8s,而
5
+ * node 直调 0.79-0.82s —— 每道 TS 门禁白付约 4 秒。
6
+ * @covers AC-TS-GATE-STARTUP-01, AC-TS-GATE-STARTUP-02, AC-TS-GATE-STARTUP-03, AC-TS-GATE-STARTUP-04
7
+ */
8
+ const fs = require('node:fs');
9
+ const path = require('node:path');
10
+ const os = require('node:os');
11
+ const { resolveTsxInvocation } = require('../gate-runner');
12
+
13
+ let tmpDir;
14
+
15
+ beforeEach(() => {
16
+ tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'xpgate-tsx-'));
17
+ });
18
+
19
+ afterEach(() => {
20
+ if (tmpDir && fs.existsSync(tmpDir)) {
21
+ fs.rmSync(tmpDir, { recursive: true, force: true });
22
+ }
23
+ });
24
+
25
+ /**
26
+ * Lay down a fake <root>/node_modules/tsx/dist/cli.mjs that exists and is readable.
27
+ *
28
+ * Failing here means the FIXTURE broke, not the resolver, so the error names the
29
+ * fixture. Swallowing it would let a setup defect surface later as "the resolver
30
+ * returned the npx fallback", which is a misleading diagnosis.
31
+ */
32
+ function plantLocalTsx(root) {
33
+ const cli = path.join(root, 'node_modules', 'tsx', 'dist', 'cli.mjs');
34
+ try {
35
+ fs.mkdirSync(path.dirname(cli), { recursive: true });
36
+ fs.writeFileSync(cli, '// fake tsx cli' + String.fromCharCode(10));
37
+ } catch (err) {
38
+ throw new Error(`fixture: could not plant tsx cli at ${cli}: ${err.message}`);
39
+ }
40
+ return cli;
41
+ }
42
+
43
+ describe('resolveTsxInvocation — AC-TS-GATE-STARTUP-01', () => {
44
+ it('uses node.exe + tsx/cli.mjs when a local tsx is installed', () => {
45
+ const cli = plantLocalTsx(tmpDir);
46
+ const { command, args } = resolveTsxInvocation(['gate.ts', '--run'], { cwd: tmpDir });
47
+
48
+ expect(command).toBe(process.execPath);
49
+ expect(args[0]).toBe(cli);
50
+ expect(args.slice(1)).toEqual(['gate.ts', '--run']);
51
+ });
52
+
53
+ it('never puts `-y` in the argv — that is the npx network-retry flag', () => {
54
+ plantLocalTsx(tmpDir);
55
+ const { args } = resolveTsxInvocation(['gate.ts'], { cwd: tmpDir });
56
+ expect(args).not.toContain('-y');
57
+ expect(args).not.toContain('tsx');
58
+ });
59
+ });
60
+
61
+ describe('resolveTsxInvocation — AC-TS-GATE-STARTUP-02', () => {
62
+ it('walks up parent directories to find a hoisted node_modules/tsx', () => {
63
+ const nested = path.join(tmpDir, 'a', 'b', 'c');
64
+ fs.mkdirSync(nested, { recursive: true });
65
+ const cli = plantLocalTsx(tmpDir);
66
+
67
+ const { args } = resolveTsxInvocation(['gate.ts'], { cwd: nested });
68
+ expect(args[0]).toBe(cli);
69
+ });
70
+
71
+ it('falls back to npm npx-cli.js (still no shell) when no tsx is installed', () => {
72
+ const { command, args } = resolveTsxInvocation(['gate.ts'], { cwd: tmpDir });
73
+
74
+ // The fallback keeps the pre-existing no-shell guarantee: node.exe runs npx's
75
+ // own JS entry. What must NOT happen is a bare `npx` (unresolvable without a
76
+ // shell on Windows) or `shell: true` (cmd.exe's 8191-char ceiling, #586).
77
+ expect(command).toBe(process.execPath);
78
+ expect(args.some((a) => String(a).includes('npx-cli.js'))).toBe(true);
79
+ expect(args).toContain('-y');
80
+ });
81
+ });
82
+
83
+ describe('resolveTsxInvocation — AC-TS-GATE-STARTUP-03', () => {
84
+ it('ignores a tsx dir that exists but has no cli.mjs (partial install)', () => {
85
+ fs.mkdirSync(path.join(tmpDir, 'node_modules', 'tsx', 'dist'), { recursive: true });
86
+ const { args } = resolveTsxInvocation(['gate.ts'], { cwd: tmpDir });
87
+ expect(args.some((a) => String(a).includes('npx-cli.js'))).toBe(true);
88
+ });
89
+
90
+ it('produces a spawnable argv: an existing file for args[0] when local', () => {
91
+ plantLocalTsx(tmpDir);
92
+ const { command, args } = resolveTsxInvocation(['gate.ts'], { cwd: tmpDir });
93
+ expect(command).toBe(process.execPath);
94
+ expect(fs.existsSync(args[0])).toBe(true);
95
+ });
96
+ });
97
+
98
+ describe('resolveTsxInvocation — AC-TS-GATE-STARTUP-04 (npm layout varies by install)', () => {
99
+ /**
100
+ * Restore `process.execPath` after the probe. Kept as a helper because the
101
+ * override is only sound if it is undone even when an assertion throws, and an
102
+ * unrestored execPath would corrupt every later test in this process.
103
+ */
104
+ function withExecPath(fakeNode, fn) {
105
+ const real = process.execPath;
106
+ Object.defineProperty(process, 'execPath', { value: fakeNode, configurable: true });
107
+ try {
108
+ return fn();
109
+ } finally {
110
+ Object.defineProperty(process, 'execPath', { value: real, configurable: true });
111
+ delete require.cache[require.resolve('../gate-runner')];
112
+ }
113
+ }
114
+
115
+ it('finds npm under lib/node_modules — the layout actions/setup-node produces on Linux', () => {
116
+ // This is the shape CI actually runs on: /opt/hostedtoolcache/node/<v>/x64/bin/node
117
+ // with npm's library at <...>/lib/node_modules/npm, not alongside the binary.
118
+ // Probe order matters only because the plain layout is tried first; what this
119
+ // asserts is that the `lib/` layout is tried at all.
120
+ const root = path.join(tmpDir, 'node-install');
121
+ const fakeNode = path.join(root, 'x64', 'bin', 'node');
122
+ const libNpm = path.join(root, 'x64', 'lib', 'node_modules', 'npm', 'bin', 'npx-cli.js');
123
+ fs.mkdirSync(path.dirname(libNpm), { recursive: true });
124
+ fs.writeFileSync(libNpm, '');
125
+
126
+ withExecPath(fakeNode, () => {
127
+ const { command, args } = resolveTsxInvocation(['gate.ts'], { cwd: tmpDir });
128
+ // A bare `npx` here is the defect: unresolvable without a shell on Windows,
129
+ // and a PATH hop that silently runs whatever npx happens to be first.
130
+ expect(command).toBe(fakeNode);
131
+ expect(args.some((a) => String(a).includes('npx-cli.js'))).toBe(true);
132
+ expect(fs.existsSync(args[0])).toBe(true);
133
+ });
134
+ });
135
+
136
+ it('finds npm alongside the binary — the Windows MSI / official tarball layout', () => {
137
+ const root = path.join(tmpDir, 'win-install');
138
+ const fakeNode = path.join(root, 'node.exe');
139
+ const plainNpm = path.join(root, 'node_modules', 'npm', 'bin', 'npx-cli.js');
140
+ fs.mkdirSync(path.dirname(plainNpm), { recursive: true });
141
+ fs.writeFileSync(plainNpm, '');
142
+
143
+ withExecPath(fakeNode, () => {
144
+ const { command, args } = resolveTsxInvocation(['gate.ts'], { cwd: tmpDir });
145
+ expect(command).toBe(fakeNode);
146
+ expect(args.some((a) => String(a).includes('npx-cli.js'))).toBe(true);
147
+ });
148
+ });
149
+ });
@@ -66,16 +66,32 @@ function hostilePathSegment() {
66
66
  return 'space $HOME `marker` "quoted"';
67
67
  }
68
68
 
69
+ // One initialised repository, shared by every test in this file.
70
+ let _gitProjectTemplate = null;
71
+
72
+ function gitProjectTemplate() {
73
+ if (_gitProjectTemplate) return _gitProjectTemplate;
74
+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'xpgate-runner-template-'));
75
+ execFileSync('git', ['init', '-q'], { cwd: dir });
76
+ execFileSync('git', ['config', 'user.email', 'test@example.com'], { cwd: dir });
77
+ execFileSync('git', ['config', 'user.name', 'XP-Gate Test'], { cwd: dir });
78
+ fs.writeFileSync(path.join(dir, 'tracked.ts'), 'const value = 1;\n');
79
+ execFileSync('git', ['add', 'tracked.ts'], { cwd: dir });
80
+ execFileSync('git', ['-c', 'core.hooksPath=/dev/null', 'commit', '-qm', 'initial'], {
81
+ cwd: dir,
82
+ });
83
+ _gitProjectTemplate = dir;
84
+ return dir;
85
+ }
86
+
69
87
  function initializeGitProject() {
70
88
  try {
71
- execFileSync('git', ['init', '-q'], { cwd: tmpProject });
72
- execFileSync('git', ['config', 'user.email', 'test@example.com'], { cwd: tmpProject });
73
- execFileSync('git', ['config', 'user.name', 'XP-Gate Test'], { cwd: tmpProject });
89
+ // Copy a pre-initialised template rather than launching five git processes.
90
+ // `init` + two `config` + `add` + `commit` is ~700 ms of pure process
91
+ // startup on Windows, and three tests rebuild this fixture. The copied tree
92
+ // already carries the identity and the initial commit.
93
+ fs.cpSync(gitProjectTemplate(), tmpProject, { recursive: true });
74
94
  writeFixture(path.join(tmpProject, 'tracked.ts'), 'const value = 1;\n');
75
- execFileSync('git', ['add', 'tracked.ts'], { cwd: tmpProject });
76
- execFileSync('git', ['-c', 'core.hooksPath=/dev/null', 'commit', '-qm', 'initial'], {
77
- cwd: tmpProject,
78
- });
79
95
  } catch (err) {
80
96
  // Without this the failure surfaces as a downstream assertion on the gate's
81
97
  // output. Name the setup step instead: a repo fixture that never initialised
@@ -42,11 +42,29 @@ function git(command, cwd) {
42
42
  }).trim();
43
43
  }
44
44
 
45
- function createRepository(dir, message) {
45
+ // A pre-initialised repository, created once per test FILE rather than once per
46
+ // test. `git init` + three `git config` + `git add` is four process launches that
47
+ // have nothing to do with what these tests assert; on Windows each launch costs
48
+ // ~130 ms, so this fixture was ~0.5 s of pure process overhead per repository and
49
+ // the file builds 20 of them (84 s measured, the single slowest test file in the
50
+ // suite). Copying the prepared tree is one filesystem operation instead.
51
+ let _repoTemplate = null;
52
+
53
+ function repoTemplate() {
54
+ if (_repoTemplate) return _repoTemplate;
55
+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'phase-transition-template-'));
46
56
  git('init --quiet --template=', dir);
47
57
  git('config core.hooksPath /dev/null', dir);
48
58
  git('config user.email "test@test.com"', dir);
49
59
  git('config user.name "Test"', dir);
60
+ _repoTemplate = dir;
61
+ return dir;
62
+ }
63
+
64
+ function createRepository(dir, message) {
65
+ // Copy the prepared template (init + config already done, so no process is
66
+ // launched for either), then make the one commit that encodes `message`.
67
+ fs.cpSync(repoTemplate(), dir, { recursive: true });
50
68
  fs.writeFileSync(path.join(dir, 'file.txt'), message);
51
69
  git('add file.txt', dir);
52
70
  git(`commit --quiet -m "${message}"`, dir);
@@ -51,6 +51,28 @@ function makeCommit(msg, dir) {
51
51
  git(`commit --no-verify -m "${msg}"`, d);
52
52
  }
53
53
 
54
+ // A repository with identity already configured, built once per test FILE
55
+ // instead of once per test. `git init` plus two `git config` launches cost
56
+ // ~130 ms each on Windows and none of it is what these tests assert; copying the
57
+ // prepared tree is one filesystem operation instead of three process launches.
58
+ let _repoTemplate = null;
59
+
60
+ /** Build the template exactly once. Never copies from itself. */
61
+ function repoTemplate() {
62
+ if (_repoTemplate) return _repoTemplate;
63
+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'rework-template-'));
64
+ git('init', dir);
65
+ git('config user.email "test@test.com"', dir);
66
+ git('config user.name "Test"', dir);
67
+ _repoTemplate = dir;
68
+ return dir;
69
+ }
70
+
71
+ /** Create a configured repo at `dir`, replacing the init + 2x config triple. */
72
+ function initRepo(dir) {
73
+ fs.cpSync(repoTemplate(), dir, { recursive: true });
74
+ }
75
+
54
76
  function daysAgo(n) {
55
77
  return new Date(Date.now() - n * 86400000).toISOString();
56
78
  }
@@ -73,6 +95,12 @@ function hoursAgo(n) {
73
95
  beforeAll(() => {
74
96
  TMP_DIR = fs.mkdtempSync(path.join(os.tmpdir(), 'rework-test-'));
75
97
  cwdSpy = vi.spyOn(process, 'cwd');
98
+ // Build the shared repo template HERE, before any test mocks process.cwd().
99
+ // repoTemplate() calls os.tmpdir(), which resolves through process.cwd(); once
100
+ // cwdSpy is stubbing it to TMP_DIR, a lazily-created template would be made
101
+ // inside TMP_DIR and then copied into itself.
102
+ _repoTemplate = null;
103
+ repoTemplate();
76
104
  });
77
105
 
78
106
  beforeEach(() => {
@@ -113,9 +141,7 @@ describe('sprint-status --rework-check (#369)', () => {
113
141
  const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'rework-b-'));
114
142
  cwdSpy.mockReturnValue(dir);
115
143
 
116
- git('init', dir);
117
- git('config user.email "test@test.com"', dir);
118
- git('config user.name "Test"', dir);
144
+ initRepo(dir);
119
145
  // 10 commits, 2 of them fixes => 20%, below the 30% threshold.
120
146
  // The count has to come from real history: the old fixture made 3 commits
121
147
  // and declared 'total_sprint_commits: 10' by hand, so the expected 20%
@@ -159,9 +185,7 @@ describe('sprint-status --rework-check (#369)', () => {
159
185
  const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'rework-c-'));
160
186
  cwdSpy.mockReturnValue(dir);
161
187
 
162
- git('init', dir);
163
- git('config user.email "test@test.com"', dir);
164
- git('config user.name "Test"', dir);
188
+ initRepo(dir);
165
189
  // 10 commits, 5 of them fixes => 50%, above the 30% threshold.
166
190
  makeCommit('fix: one', dir);
167
191
  makeCommit('fix: two', dir);
@@ -223,9 +247,7 @@ describe('sprint-status --rework-check (#369)', () => {
223
247
  const outerDir = fs.mkdtempSync(path.join(os.tmpdir(), 'rework-outer-'));
224
248
 
225
249
  for (const dir of [targetDir, outerDir]) {
226
- git('init', dir);
227
- git('config user.email "test@test.com"', dir);
228
- git('config user.name "Test"', dir);
250
+ initRepo(dir);
229
251
  }
230
252
  makeCommit('feat: target initial', targetDir);
231
253
  makeCommit('fix: target bug', targetDir);
@@ -279,9 +301,7 @@ describe('sprint-status --rework-check (#369)', () => {
279
301
  const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'rework-injection-'));
280
302
  const markerFile = path.join(dir, 'injection-marker');
281
303
  cwdSpy.mockReturnValue(dir);
282
- git('init', dir);
283
- git('config user.email "test@test.com"', dir);
284
- git('config user.name "Test"', dir);
304
+ initRepo(dir);
285
305
  makeCommit('fix: target bug', dir);
286
306
 
287
307
  writeSprintState({
@@ -86,7 +86,13 @@ const GATE_CLI_TOOLS = [
86
86
  },
87
87
  {
88
88
  tool: 'semgrep',
89
- gates: ['Gate 9 (SAST Security)'],
89
+ // Gate 10, not 9. `githooks/gate-registry.sh` is the single source of truth
90
+ // (`"sast|10|gate-10.sh|YES"`); gate 9 is Build Integrity. This entry said 9,
91
+ // which is the same drift that made #717 write a C# SAST fix into gate-9.sh —
92
+ // a fix applied to a gate that never runs. Anything reporting "which gate does
93
+ // this tool serve" has to agree with the registry or it sends the reader to
94
+ // the wrong file.
95
+ gates: ['Gate 10 (SAST Security)'],
90
96
  checkCmd: 'semgrep --version',
91
97
  install: {
92
98
  darwin: 'brew install semgrep',
package/lib/doctor.js CHANGED
@@ -24,7 +24,12 @@ const { checkUpgrade, formatUpgradeMsg } = require('./check-version.js');
24
24
  const { GATE_CLI_TOOLS, checkCliTool, getToolInstallCmd, checkBash, detectInstalledPlatforms, getSkillsDirs } = require('./detect-deps.js');
25
25
  // #505: the single source of truth for module resolution order. The hook reads a
26
26
  // generated shell projection of this same module.
27
- const { RESOLUTION_ORDER } = require('./hook-module-resolution.js');
27
+ const {
28
+ RESOLUTION_ORDER,
29
+ GATE_RESOLUTION_ORDER,
30
+ ADAPTER_DIR_ORDER,
31
+ GATE_PROBE,
32
+ } = require('./hook-module-resolution.js');
28
33
  const { inspectHookFile } = require('./hook-health.js');
29
34
  const { parseQuarantine, findPolicyViolations } = require('./flaky.js');
30
35
 
@@ -1165,18 +1170,34 @@ function resolveExecutedModuleDirs(ctx = {}) {
1165
1170
  const scriptDir = ctx.scriptDir || GLOBAL_HOOKS_DIR();
1166
1171
 
1167
1172
  const has = (dir, file) => fs.existsSync(path.join(dir, file));
1168
-
1173
+ const roots = { adapterDir: scriptDir, globalAdapterDir, projectGithooks, scriptDir };
1174
+ const dirFor = (tier) => dirForTierBase(tier.base, roots);
1175
+
1176
+ // Read the cascade from ADAPTER_DIR_ORDER instead of restating it. The order
1177
+ // used to be typed here a second time, and when the spec moved to
1178
+ // project-first this copy kept answering global-first -- so doctor reported a
1179
+ // module surface the hook had already stopped executing. That is the same
1180
+ // duplication #505 exists to prevent, one level down.
1169
1181
  let adapterDir = scriptDir;
1170
- if (has(globalAdapterDir, 'adapter-common.sh')) {
1171
- adapterDir = globalAdapterDir;
1172
- } else if (has(projectGithooks, 'adapter-common.sh')) {
1173
- adapterDir = projectGithooks;
1182
+ for (const tier of ADAPTER_DIR_ORDER) {
1183
+ const dir = dirFor(tier);
1184
+ if (dir && has(dir, tier.probe)) {
1185
+ adapterDir = dir;
1186
+ break;
1187
+ }
1174
1188
  }
1175
1189
 
1190
+ // Gate scripts: same tier list, probed for the gate sentinel rather than for
1191
+ // adapter-common.sh (GATE_RESOLUTION_ORDER's bases mirror ADAPTER_DIR_ORDER's).
1176
1192
  let gateDir = adapterDir;
1177
- if (!has(adapterDir, 'gate-3.sh')) {
1178
- if (has(projectGithooks, 'gate-3.sh')) gateDir = projectGithooks;
1179
- else if (has(scriptDir, 'gate-3.sh')) gateDir = scriptDir;
1193
+ if (!has(adapterDir, GATE_PROBE)) {
1194
+ for (const tier of ADAPTER_DIR_ORDER) {
1195
+ const dir = dirFor(tier);
1196
+ if (dir && has(dir, GATE_PROBE)) {
1197
+ gateDir = dir;
1198
+ break;
1199
+ }
1200
+ }
1180
1201
  }
1181
1202
 
1182
1203
  return { adapterDir, gateDir, globalAdapterDir, projectGithooks, scriptDir };
@@ -1259,17 +1280,60 @@ function executedModulePath(name, dirs) {
1259
1280
  const sourced = path.join(dirs.adapterDir, name);
1260
1281
  return fs.existsSync(sourced) ? sourced : null;
1261
1282
  }
1262
- const candidates = isGateModuleFile(name)
1263
- ? [path.join(dirs.gateDir, name)]
1264
- : [
1265
- path.join(dirs.adapterDir, name),
1266
- path.join(dirs.adapterDir, 'adapters', name),
1267
- path.join(dirs.projectGithooks, 'adapters', name),
1268
- path.join(dirs.scriptDir, 'adapters', name),
1269
- ];
1283
+ // The candidate chain is projected from RESOLUTION_ORDER rather than typed out
1284
+ // here. This used to be a second copy of the order, and it went stale the
1285
+ // moment the tiers changed: it began the chain with `adapterDir/<name>.sh`
1286
+ // (the FLAT layout) even when ADAPTER_DIR was the project tier, so a stray file
1287
+ // at the repo root shadowed the repo's own nested adapter.
1288
+ if (isGateModuleFile(name)) {
1289
+ // Gate modules have exactly one executed location: whatever GATE_DIR resolved
1290
+ // to. GATE_DIR already ran the full tier fallback in
1291
+ // resolveExecutedModuleDirs(), so re-walking the tiers here would report a
1292
+ // copy that tier holds but the gate suite does not actually run from.
1293
+ const gatePath = path.join(dirs.gateDir, name);
1294
+ return fs.existsSync(gatePath) ? gatePath : null;
1295
+ }
1296
+ // Adapter templates carry their own extension ('{name}.sh'), so the
1297
+ // substitution needs the bare stem here -- unlike the gate call above, which
1298
+ // takes the filename as-is. Same split as the hook's
1299
+ // resolve_adapter_path ("bare language name") vs _hook_resolve.
1300
+ const stem = name.replace(/\.[^./\\]+$/, '');
1301
+ const candidates = RESOLUTION_ORDER
1302
+ .map((tier) => {
1303
+ const root = dirForTierBase(tier.base, dirs);
1304
+ return root ? path.join(root, tier.template.replace('{name}', stem)) : null;
1305
+ })
1306
+ .filter(Boolean);
1270
1307
  return candidates.find((candidate) => fs.existsSync(candidate)) || null;
1271
1308
  }
1272
1309
 
1310
+ /**
1311
+ * The directory a resolution tier's `base` names, from
1312
+ * `resolveExecutedModuleDirs()` output.
1313
+ *
1314
+ * An unknown base returns null rather than ''. A '' base makes `path.join` emit a
1315
+ * relative path, and `existsSync` then probes the CWD -- silently testing a
1316
+ * different tree instead of failing.
1317
+ *
1318
+ * @param {string} base
1319
+ * @param {ReturnType<typeof resolveExecutedModuleDirs>} dirs
1320
+ * @returns {string|null}
1321
+ */
1322
+ function dirForTierBase(base, dirs) {
1323
+ switch (base) {
1324
+ case 'ADAPTER_DIR':
1325
+ return dirs.adapterDir;
1326
+ case 'GLOBAL_ADAPTER_DIR':
1327
+ return dirs.globalAdapterDir;
1328
+ case 'PROJECT_GITHOOKS':
1329
+ return dirs.projectGithooks;
1330
+ case 'SCRIPT_DIR':
1331
+ return dirs.scriptDir;
1332
+ default:
1333
+ return null;
1334
+ }
1335
+ }
1336
+
1273
1337
  /**
1274
1338
  * Which tier an executed copy came from, so a FAIL says where it ran from.
1275
1339
  */
@@ -356,11 +356,103 @@ function resolveGateCwd(targetPath) {
356
356
  * plain argv, no shell, no batch wrapper.
357
357
  */
358
358
  function resolveNpxInvocation(args) {
359
- const npxCli = path.join(path.dirname(process.execPath), 'node_modules', 'npm', 'bin', 'npx-cli.js');
360
- if (fs.existsSync(npxCli)) return [process.execPath, [npxCli, ...args]];
359
+ const npxCli = findNpxCli();
360
+ if (npxCli) return [process.execPath, [npxCli, ...args]];
361
361
  return ['npx', args];
362
362
  }
363
363
 
364
+ /**
365
+ * npm's own shell-free entry point (`npx-cli.js`), or null.
366
+ *
367
+ * The previous form looked only in `dirname(process.execPath)/node_modules/npm`,
368
+ * which is the layout of a Node installed from the Windows MSI or the official
369
+ * tarball. GitHub's `actions/setup-node` on Linux runs node from
370
+ * `/opt/hostedtoolcache/node/<version>/x64/bin/node`, where npm's library lives
371
+ * under `lib/node_modules/npm` instead — so the probe missed, the fallback became
372
+ * a bare `npx`, and that is unresolvable without a shell on Windows and a PATH hop
373
+ * everywhere else. CI caught it as two red assertions; the same install shape
374
+ * would have made the gate spawn the wrong thing on a developer's Linux box.
375
+ *
376
+ * Searches the same way `findTsxCli` does — one directory at a time, both the
377
+ * plain and the `lib/` npm layout — because "npm sits next to node" is an
378
+ * assumption about how Node was packaged, not a guarantee.
379
+ */
380
+ function findNpxCli() {
381
+ let dir = path.dirname(process.execPath);
382
+ for (let depth = 0; depth < TSX_SEARCH_DEPTH; depth += 1) {
383
+ for (const npmRoot of ['node_modules', path.join('lib', 'node_modules')]) {
384
+ const candidate = path.join(dir, npmRoot, 'npm', 'bin', 'npx-cli.js');
385
+ if (fs.existsSync(candidate)) return candidate;
386
+ }
387
+ const parent = path.dirname(dir);
388
+ if (parent === dir) break;
389
+ dir = parent;
390
+ }
391
+ return null;
392
+ }
393
+
394
+ /**
395
+ * How deep to look for a hoisted `node_modules/tsx` before giving up.
396
+ *
397
+ * Four is enough for the layouts that actually occur — `<repo>/node_modules`,
398
+ * `<repo>/src/npm-package/node_modules`, a git worktree's shared parent, and one
399
+ * level of monorepo nesting — without turning a miss into an unbounded walk up to
400
+ * the filesystem root.
401
+ */
402
+ const TSX_SEARCH_DEPTH = 4;
403
+
404
+ /**
405
+ * The nearest installed `tsx` CLI entry, or null.
406
+ *
407
+ * #779: every TypeScript gate used to be launched as `npx -y tsx <entry> --run`, and
408
+ * `npx -y` re-resolves where the package lives on EVERY call. Measured on this
409
+ * machine: `npx -y tsx --version` takes 4547-5811 ms while `node <tsx-cli> --version`
410
+ * takes 787-821 ms. That is ~4 s of pure package-resolution paid once per TS gate,
411
+ * and `xp-gate check --all` runs several — which is how a one-file project reached
412
+ * 117 s (the /tmp measurement in the governance review).
413
+ *
414
+ * Searching upward matters because the CLI is normally invoked from a CONSUMER
415
+ * project whose `node_modules` lives at the project root, while the gate module is
416
+ * resolved from the xp-gate install.
417
+ *
418
+ * @param {string} [cwd] directory to start from; defaults to process.cwd()
419
+ * @returns {string|null}
420
+ */
421
+ function findTsxCli(cwd = process.cwd()) {
422
+ let dir = path.resolve(cwd);
423
+ for (let depth = 0; depth < TSX_SEARCH_DEPTH; depth += 1) {
424
+ const candidate = path.join(dir, 'node_modules', 'tsx', 'dist', 'cli.mjs');
425
+ if (fs.existsSync(candidate)) return candidate;
426
+ const parent = path.dirname(dir);
427
+ if (parent === dir) break;
428
+ dir = parent;
429
+ }
430
+ return null;
431
+ }
432
+
433
+ /**
434
+ * The executable + argv for running one TypeScript gate module.
435
+ *
436
+ * Prefers `node <tsx-cli> <args>`: no shim, no shell, no network, and no repeated
437
+ * package resolution. Falls back to npm's own `npx-cli.js` (still under the current
438
+ * node binary, still shell-free) only when no tsx is installed — the shape
439
+ * `resolveNpxInvocation` already guarantees.
440
+ *
441
+ * A `tsx/` directory with no `dist/cli.mjs` is treated as "not installed": a
442
+ * half-written install would otherwise be spawned and fail with a message about
443
+ * missing files, which reads like a gate defect rather than an install one.
444
+ *
445
+ * @param {string[]} args tsx argv (entry path, then the gate's own flags)
446
+ * @param {{cwd?: string}} [opts]
447
+ * @returns {{command: string, args: string[], viaNpx: boolean}}
448
+ */
449
+ function resolveTsxInvocation(args, opts = {}) {
450
+ const tsxCli = findTsxCli(opts.cwd);
451
+ if (tsxCli) return { command: process.execPath, args: [tsxCli, ...args], viaNpx: false };
452
+ const [command, argv] = resolveNpxInvocation(['-y', 'tsx', ...args]);
453
+ return { command, args: argv, viaNpx: true };
454
+ }
455
+
364
456
  /**
365
457
  * A project-local gate variant, if the project declares one.
366
458
  *
@@ -431,7 +523,7 @@ function runTsGate(gateModule, targetPath, opts = {}) {
431
523
  return GATE_NOT_RUN;
432
524
  }
433
525
 
434
- const args = ['-y', 'tsx', impl.entry, '--run'];
526
+ const args = [impl.entry, '--run'];
435
527
  if (targetPath) args.push('--cwd', targetPath);
436
528
 
437
529
  // spawnSync reports a spawn failure (npx missing) on `error`, throws only on a
@@ -443,7 +535,9 @@ function runTsGate(gateModule, targetPath, opts = {}) {
443
535
  // malformed argv, and reports a killed child (timeout, signal) as a null status.
444
536
  // All three mean "the gate did not report a verdict", which must not be read as
445
537
  // success: a gate that never ran is not a gate that passed.
446
- const [command, commandArgs] = resolveNpxInvocation(args);
538
+ // #779: node + tsx's own CLI, not `npx -y tsx`. Same no-shell guarantee, no
539
+ // per-gate package re-resolution (~4 s saved per TS gate).
540
+ const { command, args: commandArgs, viaNpx } = resolveTsxInvocation(args, { cwd: targetCwd });
447
541
  try {
448
542
  const result = spawnSync(command, commandArgs, {
449
543
  stdio: 'inherit',
@@ -451,12 +545,12 @@ function runTsGate(gateModule, targetPath, opts = {}) {
451
545
  timeout: TS_GATE_TIMEOUT_MS,
452
546
  });
453
547
  if (result.error) {
454
- console.error(`Gate ${gateModule}: failed to run npx tsx: ${result.error.message}`);
548
+ console.error(`Gate ${gateModule}: failed to run tsx (${viaNpx ? 'npx fallback' : 'local cli'}): ${result.error.message}`);
455
549
  return 1;
456
550
  }
457
551
  return result.status === null ? 1 : result.status;
458
552
  } catch (err) {
459
- console.error(`Gate ${gateModule}: could not spawn npx tsx: ${err.message}`);
553
+ console.error(`Gate ${gateModule}: could not spawn tsx (${viaNpx ? 'npx fallback' : 'local cli'}): ${err.message}`);
460
554
  return 1;
461
555
  }
462
556
  }
@@ -798,4 +892,4 @@ async function runGate(gateId, targetPath, opts = {}) {
798
892
  return 1;
799
893
  }
800
894
 
801
- module.exports = { findConsumerGateVariant, GATE_REGISTRY, GATE_NOT_RUN, getGateInfo, getAllGates, runGate, resolveAlias, getAliases, runGateAdapter, findTsGateEntry, resolveGateScript, SOURCE_FILE_EXTENSIONS, resolveAllModeChangedFiles, describeEmptyChangedFiles, describeChangedFilesScope };
895
+ module.exports = { findConsumerGateVariant, GATE_REGISTRY, GATE_NOT_RUN, getGateInfo, getAllGates, runGate, resolveAlias, getAliases, runGateAdapter, findTsGateEntry, resolveGateScript, resolveTsxInvocation, findTsxCli, SOURCE_FILE_EXTENSIONS, resolveAllModeChangedFiles, describeEmptyChangedFiles, describeChangedFilesScope };
@@ -91,19 +91,31 @@ const GATE_RESOLUTION_ORDER = Object.freeze([
91
91
  * tree every later lookup searches, so it must have one definition.
92
92
  *
93
93
  * `probe` is the file whose presence in `base` makes that tier win.
94
+ *
95
+ * PRECEDENCE IS PROJECT-FIRST, on purpose. The two install modes exist to make
96
+ * the global copy a DEFAULT, not an override: a repo that never ran
97
+ * `xp-gate init` gets the global gate suite, and a repo that carries its own
98
+ * `githooks/` gets that one instead. The tiers used to be tried global-first,
99
+ * which made every per-project `githooks/` unreachable on any machine with a
100
+ * global install -- including this repo, whose own gate scripts therefore never
101
+ * ran while `git log` said they had. A project copy that cannot win is not a
102
+ * customisation, it is dead weight (#495 AC-495-23).
103
+ *
104
+ * Narrow -> broad: project (specific to this repo) beats global (machine-wide
105
+ * default) beats the hook's own directory (last resort).
94
106
  */
95
107
  const ADAPTER_DIR_ORDER = Object.freeze([
96
108
  Object.freeze({
97
- tier_id: 'global',
98
- base: 'GLOBAL_ADAPTER_DIR',
109
+ tier_id: 'project',
110
+ base: 'PROJECT_GITHOOKS',
99
111
  probe: 'adapter-common.sh',
100
- comment: '~/.config/xp-gate/adapters — global install',
112
+ comment: '<repo>/githooks — per-project init; OVERRIDES the global install',
101
113
  }),
102
114
  Object.freeze({
103
- tier_id: 'project',
104
- base: 'PROJECT_GITHOOKS',
115
+ tier_id: 'global',
116
+ base: 'GLOBAL_ADAPTER_DIR',
105
117
  probe: 'adapter-common.sh',
106
- comment: '<repo>/githooks — per-project init',
118
+ comment: '~/.config/xp-gate/adapters — global install (the default)',
107
119
  }),
108
120
  Object.freeze({
109
121
  tier_id: 'script',