@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
@@ -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({
@@ -3,7 +3,7 @@
3
3
  * @intent doctor 判技能新鲜度必须行尾无关:frontmatter 正则只认 LF + 退化分支做
4
4
  * 字节比较,导致 autocrlf 工作树下 12/13 个技能被假报 Outdated,真差异
5
5
  * 反而被噪声淹没(#439)
6
- * @covers AC-439-01, AC-439-02, AC-439-03
6
+ * @covers AC-439-01, AC-439-02, AC-439-03, AC-439-04, AC-718-01, AC-718-02, AC-718-03
7
7
  */
8
8
  const fs = require('fs');
9
9
  const path = require('path');
@@ -196,9 +196,17 @@ describe('doctor-tui installed skills enumerate the filesystem (#635)', () => {
196
196
  /** Deploy a real bundled skill into one platform's skills dir. */
197
197
  function deploy(platformDirs, name) {
198
198
  const dir = path.join(tmpHome, ...platformDirs, name);
199
- fs.mkdirSync(dir, { recursive: true });
200
- const bundled = fs.readFileSync(path.join(bundledSkillsDir, name, 'SKILL.md'), 'utf8');
201
- fs.writeFileSync(path.join(dir, 'SKILL.md'), bundled);
199
+ try {
200
+ fs.mkdirSync(dir, { recursive: true });
201
+ const bundled = fs.readFileSync(path.join(bundledSkillsDir, name, 'SKILL.md'), 'utf8');
202
+ fs.writeFileSync(path.join(dir, 'SKILL.md'), bundled);
203
+ } catch (error) {
204
+ // Naming the skill keeps a misplaced fixture from looking like a
205
+ // doctor() behaviour failure. `cause` keeps the original error's code and
206
+ // stack reachable instead of flattening it to a message.
207
+ const reason = error instanceof Error ? error.message : String(error);
208
+ throw new Error(`Failed to deploy bundled skill ${name}: ${reason}`, { cause: error });
209
+ }
202
210
  }
203
211
 
204
212
  // AC-635-01: a machine with skills deployed and NO installedSkills config key
@@ -325,8 +333,15 @@ describe('doctor-tui skill freshness #681 equal version, different content', ()
325
333
 
326
334
  function installSkill(name, content) {
327
335
  const dir = path.join(tmpHome, '.config', 'opencode', 'skills', name);
328
- fs.mkdirSync(dir, { recursive: true });
329
- fs.writeFileSync(path.join(dir, 'SKILL.md'), content);
336
+ try {
337
+ fs.mkdirSync(dir, { recursive: true });
338
+ fs.writeFileSync(path.join(dir, 'SKILL.md'), content);
339
+ } catch (error) {
340
+ // `cause` keeps the original error's code and stack reachable instead of
341
+ // flattening it to a message string.
342
+ const reason = error instanceof Error ? error.message : String(error);
343
+ throw new Error(`Failed to install test skill ${name}: ${reason}`, { cause: error });
344
+ }
330
345
  }
331
346
 
332
347
  function runFreshness(name) {
@@ -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
  }
@@ -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
@@ -0,0 +1,204 @@
1
+ /**
2
+ * @test REQ-767
3
+ * @intent `xp-gate init` 往项目里写 githooks 适配器副本、.xp-gate/ 模块镜像和生成的
4
+ * .xp-gate-config.json,却从不写 .gitignore:这些机器相关的产物全部以未跟踪
5
+ * 条目出现在 git status 里,file-hygiene/debt 门禁把生成物当成未提交源码,
6
+ * 造成用户无法自行修复的 Gate 6 零容忍 BLOCK(#767)
7
+ * @covers AC-767-01, AC-767-02, AC-767-03, AC-767-04
8
+ */
9
+ const fs = require('fs');
10
+ const path = require('path');
11
+ const os = require('os');
12
+
13
+ const { ensureGitignoreEntries, gitignoreEntriesForInit } = require('../init');
14
+
15
+ function makeProject(gitignoreContent) {
16
+ const root = fs.mkdtempSync(path.join(os.tmpdir(), 'xpgate-gitignore-'));
17
+ if (gitignoreContent !== undefined) {
18
+ fs.writeFileSync(path.join(root, '.gitignore'), gitignoreContent);
19
+ }
20
+ return root;
21
+ }
22
+
23
+ describe('init .gitignore management (#767)', () => {
24
+ let root;
25
+
26
+ afterEach(() => {
27
+ if (root) fs.rmSync(root, { recursive: true, force: true });
28
+ root = null;
29
+ });
30
+
31
+ it('creates .gitignore when the project has none', () => {
32
+ root = makeProject(undefined);
33
+ const added = ensureGitignoreEntries(root);
34
+
35
+ expect(added.length).toBeGreaterThan(0);
36
+ expect(fs.readFileSync(path.join(root, '.gitignore'), 'utf8')).toContain('.xp-gate-config.json');
37
+ });
38
+
39
+ it('keeps the user\'s existing rules untouched', () => {
40
+ root = makeProject('node_modules/\ndist/\n');
41
+ ensureGitignoreEntries(root);
42
+
43
+ const content = fs.readFileSync(path.join(root, '.gitignore'), 'utf8');
44
+ expect(content.startsWith('node_modules/\ndist/\n')).toBe(true);
45
+ });
46
+
47
+ // Re-running init is a documented repair action; a second appended block would
48
+ // grow the file on every run and make the diff look like a real change.
49
+ it('is idempotent — a second run adds nothing', () => {
50
+ root = makeProject('node_modules/\n');
51
+ const first = ensureGitignoreEntries(root);
52
+ const second = ensureGitignoreEntries(root);
53
+
54
+ expect(first.length).toBeGreaterThan(0);
55
+ expect(second).toEqual([]);
56
+ });
57
+
58
+ // The empty-return above is not sufficient proof of idempotency: the first
59
+ // version excluded comment lines from the presence set, so every run appended
60
+ // another copy of the section headers while still returning []. Assert on the
61
+ // FILE so a header-only regression cannot hide behind an empty return value.
62
+ it('is idempotent at the file level — repeated runs leave the file byte-identical', () => {
63
+ root = makeProject('node_modules/\n');
64
+ ensureGitignoreEntries(root);
65
+ const afterFirst = fs.readFileSync(path.join(root, '.gitignore'), 'utf8');
66
+ ensureGitignoreEntries(root);
67
+ ensureGitignoreEntries(root);
68
+
69
+ expect(fs.readFileSync(path.join(root, '.gitignore'), 'utf8')).toBe(afterFirst);
70
+ const header = '# xp-gate: generated by `xp-gate init`';
71
+ expect(afterFirst.split(header).length - 1).toBe(1);
72
+ });
73
+
74
+ it('adds only the rules that are missing', () => {
75
+ root = makeProject('.xp-gate-config.json\n');
76
+ const added = ensureGitignoreEntries(root);
77
+
78
+ expect(added).not.toContain('.xp-gate-config.json');
79
+ expect(added).toContain('.xp-gate/lint-baseline.json');
80
+ });
81
+
82
+ it('does not append a rule already present with surrounding whitespace', () => {
83
+ root = makeProject(' .xp-gate-config.json \n');
84
+ expect(ensureGitignoreEntries(root)).not.toContain('.xp-gate-config.json');
85
+ });
86
+
87
+ // The regression guard that matters most: the hook entrypoints and the gate
88
+ // registry are real project source. Ignoring them would un-version exactly the
89
+ // files a user needs to customise and the file that binds gate names to scripts.
90
+ it('never ignores the committable githooks entrypoints or the registry', () => {
91
+ const patterns = gitignoreEntriesForInit();
92
+ for (const mustStayTracked of [
93
+ 'githooks/pre-commit',
94
+ 'githooks/pre-push',
95
+ 'githooks/adapter-common.sh',
96
+ 'githooks/gate-registry.sh',
97
+ 'githooks/gate-3.sh',
98
+ ]) {
99
+ expect(patterns).not.toContain(mustStayTracked);
100
+ }
101
+ // No broad `githooks/` rule either — that would swallow the entrypoints.
102
+ expect(patterns).not.toContain('githooks/');
103
+ });
104
+
105
+ it('ignores the per-language adapter copies that init installs', () => {
106
+ const patterns = gitignoreEntriesForInit();
107
+ expect(patterns).toContain('githooks/csharp.sh');
108
+ expect(patterns).toContain('githooks/adapters/gate-*.sh');
109
+ });
110
+
111
+ // Appending must not corrupt a file whose last line lacks a newline.
112
+ it('separates the block from a file with no trailing newline', () => {
113
+ root = makeProject('node_modules/');
114
+ ensureGitignoreEntries(root);
115
+
116
+ const content = fs.readFileSync(path.join(root, '.gitignore'), 'utf8');
117
+ expect(content).toContain('node_modules/\n');
118
+ expect(content.split('\n')).toContain('.xp-gate-config.json');
119
+ });
120
+ });
121
+
122
+ /**
123
+ * @test REQ-767
124
+ * @intent Delphi round 2 (FC-05): merging the block used a bare writeFileSync, which
125
+ * truncates before writing. An ENOSPC or a killed process mid-write would
126
+ * leave the user's .gitignore truncated — destroying the rules this feature
127
+ * promises to preserve, in a file xp-gate does not own. A temp file plus
128
+ * rename is atomic within a directory: the file is either the old content or
129
+ * the complete new content.
130
+ * @covers AC-767-05
131
+ */
132
+ describe('init .gitignore write is atomic (#767)', () => {
133
+ let root;
134
+
135
+ afterEach(() => {
136
+ if (root) fs.rmSync(root, { recursive: true, force: true });
137
+ root = null;
138
+ });
139
+
140
+ it('never leaves a truncated .gitignore when the write fails', () => {
141
+ root = makeProject('node_modules/\ndist/\n');
142
+ const original = fs.readFileSync(path.join(root, '.gitignore'), 'utf8');
143
+ const writeSpy = vi.spyOn(fs, 'writeFileSync').mockImplementation(() => {
144
+ throw Object.assign(new Error('ENOSPC: no space left on device'), { code: 'ENOSPC' });
145
+ });
146
+
147
+ expect(() => ensureGitignoreEntries(root)).toThrow(/ENOSPC/);
148
+ writeSpy.mockRestore();
149
+
150
+ // The user's rules survive untouched: the failed write went to the temp file.
151
+ expect(fs.readFileSync(path.join(root, '.gitignore'), 'utf8')).toBe(original);
152
+ });
153
+
154
+ it('leaves no temp file behind after a successful write', () => {
155
+ root = makeProject('node_modules/\n');
156
+ ensureGitignoreEntries(root);
157
+
158
+ expect(fs.existsSync(path.join(root, '.gitignore.xp-gate-tmp'))).toBe(false);
159
+ });
160
+
161
+ // Delphi round 1 (CI-02): init resolved the gitignore root from process.cwd() while
162
+ // installLocal resolved it from the .git directory. Running from a subdirectory
163
+ // therefore wrote .gitignore next to the caller while the adapters landed at the
164
+ // repo root — the rules guarded a tree with no generated files. This pins the
165
+ // contract the fix relies on: the helper obeys the root it is given.
166
+ it('writes to the root it is given, not to the current working directory', () => {
167
+ root = makeProject('node_modules/\n');
168
+ const subdir = path.join(root, 'packages', 'app');
169
+ fs.mkdirSync(subdir, { recursive: true });
170
+ const cwdSpy = vi.spyOn(process, 'cwd').mockReturnValue(subdir);
171
+
172
+ ensureGitignoreEntries(root);
173
+
174
+ expect(fs.existsSync(path.join(root, '.gitignore'))).toBe(true);
175
+ expect(fs.existsSync(path.join(subdir, '.gitignore'))).toBe(false);
176
+ cwdSpy.mockRestore();
177
+ });
178
+
179
+ // Delphi round 1 (CI-03): the original wiring swallowed every error, so a read-only
180
+ // checkout left the user in the exact #767 state while init still reported success.
181
+ // The helper must surface the failure rather than absorb it.
182
+ it('propagates a write failure instead of reporting success', () => {
183
+ root = makeProject('node_modules/\n');
184
+ const writeSpy = vi.spyOn(fs, 'writeFileSync').mockImplementation(() => {
185
+ throw new Error('EACCES: permission denied');
186
+ });
187
+
188
+ expect(() => ensureGitignoreEntries(root)).toThrow(/EACCES/);
189
+ writeSpy.mockRestore();
190
+ });
191
+
192
+ // The returned list is what init reports as "N entries added", so it must count
193
+ // RULES. Section headers are written to the file but would inflate that number and
194
+ // read to the user as ignored files that are not ignore rules.
195
+ it('reports rules only — section comments are written but never counted', () => {
196
+ root = makeProject('node_modules/\n');
197
+ const added = ensureGitignoreEntries(root);
198
+
199
+ expect(added.length).toBeGreaterThan(0);
200
+ expect(added.filter((line) => line.startsWith('#'))).toEqual([]);
201
+ const written = fs.readFileSync(path.join(root, '.gitignore'), 'utf8');
202
+ expect(written).toContain('# xp-gate: generated by');
203
+ });
204
+ });
@@ -22,9 +22,18 @@ describe('init', () => {
22
22
  tmpProject = fs.mkdtempSync(path.join(os.tmpdir(), 'xpgate-proj-'));
23
23
  process.env.HOME = tmpHome;
24
24
  vi.resetModules();
25
- delete require.cache[require.resolve('../init')];
26
- delete require.cache[require.resolve('../detect-deps.js')];
27
- delete require.cache[require.resolve('../shared-paths')];
25
+ // Evict EVERY cached module under lib/, not just the three names below.
26
+ // baseline.js / language-tools.js / bootstrap.js capture
27
+ // `const { execSync } = require('child_process')` AT LOAD TIME. Once test A
28
+ // loads one of them while the execSync spy is installed, the cached module
29
+ // keeps that (by then restored) reference -- so every LATER test reaching
30
+ // the same code path calls the REAL execSync and launches checkov/semgrep
31
+ // for real (7.9 s / 3.8 s each). Deleting three fixed names never evicts them.
32
+ // Built from char code 92 so no escape sequence is involved.
33
+ const __sep = String.fromCharCode(92);
34
+ for (const k of Object.keys(require.cache)) {
35
+ if (k.split(__sep).join('/').includes('/npm-package/lib/')) delete require.cache[k];
36
+ }
28
37
  logSpy = vi.spyOn(console, 'log').mockImplementation(() => {});
29
38
  warnSpy = vi.spyOn(console, 'warn').mockImplementation(() => {});
30
39
  errorSpy = vi.spyOn(console, 'error').mockImplementation(() => {});
@@ -38,6 +47,18 @@ describe('init', () => {
38
47
  }
39
48
  return { status: 0, stdout: Buffer.from(''), stderr: Buffer.from('') };
40
49
  });
50
+ // Mock execSync BY DEFAULT so init()'s tool probes don't really execute.
51
+ // init() unconditionally runs checkBash() + printCliToolStatus() +
52
+ // probeGitleaksNotice() before ANY mode branch (even `init([])` printing
53
+ // usage). Those probe GATE_CLI_TOOLS via checkCliTool(), whose
54
+ // `where <tool>` + `<tool> --version` really launch the tools. On this box
55
+ // `checkov --version` (a heavy Python package) alone took ~7.9 s and
56
+ // `semgrep --version` ~3.8 s, so 27 tests x ~14 s of probes = 383 s wall.
57
+ // Returning '' makes every probe fail FAST (where -> '', --version -> ''),
58
+ // so checkCliTool() reports {available:false} with zero subprocess work.
59
+ // The per-test mockExecSuccess()/mockExecGitDirOnly()/mockExecFail() still
60
+ // re-spyOn execSync and override this for the git-dir/config cases.
61
+ vi.spyOn(childProcess, 'execSync').mockImplementation(() => '');
41
62
  });
42
63
 
43
64
  afterEach(() => {