@boyingliu01/xp-gate 0.37.3 → 0.38.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (116) hide show
  1. package/adapter-common.sh +12 -2
  2. package/adapters/csharp.sh +73 -2
  3. package/adapters/dart.sh +13 -0
  4. package/adapters/go.sh +5 -0
  5. package/adapters/iac.sh +46 -3
  6. package/adapters/java.sh +6 -0
  7. package/adapters/kotlin.sh +6 -0
  8. package/adapters/shell.sh +119 -34
  9. package/adapters/swift.sh +6 -0
  10. package/adapters/typescript.sh +98 -34
  11. package/bin/xp-gate.js +48 -2
  12. package/gate-10.sh +99 -26
  13. package/gate-12-file-hygiene.sh +13 -1
  14. package/gate-registry.sh +197 -0
  15. package/gates/python-health.ts +67 -29
  16. package/hooks/adapter-common.sh +12 -2
  17. package/hooks/deploy-manifest.sh +100 -0
  18. package/hooks/gate-10.sh +99 -26
  19. package/hooks/gate-12-file-hygiene.sh +13 -1
  20. package/hooks/gate-driver.sh +120 -0
  21. package/hooks/gate-entries/gate-0-entry.sh +825 -0
  22. package/hooks/gate-entries/gate-1-entry.sh +767 -0
  23. package/hooks/gate-entries/gate-10-entry.sh +52 -0
  24. package/hooks/gate-entries/gate-11-entry.sh +120 -0
  25. package/hooks/gate-entries/gate-12-entry.sh +44 -0
  26. package/hooks/gate-entries/gate-12b-entry.sh +178 -0
  27. package/hooks/gate-entries/gate-12c-entry.sh +80 -0
  28. package/hooks/gate-entries/gate-13-entry.sh +584 -0
  29. package/hooks/gate-entries/gate-2-entry.sh +199 -0
  30. package/hooks/gate-entries/gate-3-entry.sh +53 -0
  31. package/hooks/gate-entries/gate-4-entry.sh +46 -0
  32. package/hooks/gate-entries/gate-5-entry.sh +1729 -0
  33. package/hooks/gate-entries/gate-6-entry.sh +658 -0
  34. package/hooks/gate-entries/gate-7-entry.sh +41 -0
  35. package/hooks/gate-entries/gate-8-entry.sh +33 -0
  36. package/hooks/gate-entries/gate-9-entry.sh +307 -0
  37. package/hooks/gate-entries/subdir-restore.sh +27 -0
  38. package/hooks/gate-registry.sh +51 -15
  39. package/hooks/hook-module-resolution.sh +73 -0
  40. package/hooks/install.sh +135 -0
  41. package/hooks/lib/now-ms.sh +55 -19
  42. package/hooks/lib/toolchain-path.sh +50 -6
  43. package/hooks/pre-commit +256 -5091
  44. package/hooks/pre-push +212 -25
  45. package/lib/__tests__/arch-config-template.test.js +190 -0
  46. package/lib/__tests__/baseline-shell-scope.test.js +60 -0
  47. package/lib/__tests__/crap-cli.test.js +14 -3
  48. package/lib/__tests__/deploy-manifest-check-wired.test.js +138 -0
  49. package/lib/__tests__/deploy-manifest-completeness.test.js +151 -0
  50. package/lib/__tests__/deploy-manifest-consumers-adapter-uninstall.test.js +40 -0
  51. package/lib/__tests__/deploy-manifest-consumers-no-private-lists.test.js +74 -0
  52. package/lib/__tests__/deploy-manifest-projection.test.js +66 -0
  53. package/lib/__tests__/deploy-manifest-shell-parity.test.js +108 -0
  54. package/lib/__tests__/deploy-manifest.test.js +97 -0
  55. package/lib/__tests__/doctor.test.js +51 -7
  56. package/lib/__tests__/gate-coverage.test.js +79 -12
  57. package/lib/__tests__/gate-numbering.test.js +28 -1
  58. package/lib/__tests__/install-sh-deploy-manifest.test.js +80 -0
  59. package/lib/__tests__/mirror-sync.test.js +45 -3
  60. package/lib/__tests__/npm-package.test.js +10 -7
  61. package/lib/__tests__/sastd-client.test.js +452 -0
  62. package/lib/__tests__/shared-utils-copyHooks-manifest.test.js +69 -0
  63. package/lib/__tests__/sprint-status-rework.test.js +1 -0
  64. package/lib/arch-config-template.js +87 -0
  65. package/lib/baseline.js +54 -2
  66. package/lib/deploy-manifest.js +174 -0
  67. package/lib/doctor.js +46 -14
  68. package/lib/gate-capability.js +291 -0
  69. package/lib/gate-coverage.js +194 -74
  70. package/lib/gate-identity.js +349 -0
  71. package/lib/gate-runner.js +11 -1
  72. package/lib/hook-module-resolution.js +27 -0
  73. package/lib/init.js +72 -5
  74. package/lib/mattpocock-license-verdict.json +1 -1
  75. package/lib/sastd-client.js +534 -0
  76. package/lib/shared-utils.js +31 -9
  77. package/lib/uninstall.js +10 -7
  78. package/lib/update-hooks.js +27 -18
  79. package/mock-policy/AGENTS.md +1 -1
  80. package/mutation/AGENTS.md +1 -1
  81. package/package.json +3 -1
  82. package/plugins/claude-code/.claude-plugin/plugin.json +1 -1
  83. package/plugins/claude-code/skills/delphi-review/AGENTS.md +1 -1
  84. package/plugins/claude-code/skills/sprint-flow/AGENTS.md +1 -1
  85. package/plugins/claude-code/skills/test-specification-alignment/AGENTS.md +1 -1
  86. package/plugins/dsh/package.json +1 -1
  87. package/plugins/dsh/skills/delphi-review/AGENTS.md +1 -1
  88. package/plugins/dsh/skills/sprint-flow/AGENTS.md +1 -1
  89. package/plugins/dsh/skills/test-specification-alignment/AGENTS.md +1 -1
  90. package/plugins/opencode/package.json +1 -1
  91. package/plugins/opencode/skills/delphi-review/AGENTS.md +1 -1
  92. package/plugins/opencode/skills/sprint-flow/AGENTS.md +1 -1
  93. package/plugins/opencode/skills/test-specification-alignment/AGENTS.md +1 -1
  94. package/plugins/qoder/plugin.json +1 -1
  95. package/plugins/qoder/skills/delphi-review/AGENTS.md +1 -1
  96. package/plugins/qoder/skills/sprint-flow/AGENTS.md +1 -1
  97. package/plugins/qoder/skills/test-specification-alignment/AGENTS.md +1 -1
  98. package/principles/AGENTS.md +1 -1
  99. package/principles/__tests__/analyzer.test.ts +2 -1
  100. package/principles/__tests__/config-enforcement.test.ts +1 -0
  101. package/principles/__tests__/types.test.ts +1 -0
  102. package/principles/adapters/base.ts +14 -1
  103. package/principles/adapters/duplication.ts +134 -0
  104. package/principles/rules/__tests__/clean-code/large-file.test.ts +2 -1
  105. package/principles/rules/clean-code/code-duplication.ts +75 -9
  106. package/principles/types.ts +39 -0
  107. package/scripts/__tests__/check-mattpocock-license.test.js +36 -3
  108. package/scripts/__tests__/sync-package-content.test.js +12 -2
  109. package/scripts/generate-mirrors.cjs +125 -0
  110. package/scripts/sync-package-content.js +64 -20
  111. package/skills/delphi-review/AGENTS.md +1 -1
  112. package/skills/sprint-flow/AGENTS.md +1 -1
  113. package/skills/test-specification-alignment/AGENTS.md +1 -1
  114. package/adapters/gate-9.sh +0 -245
  115. package/gate-9.sh +0 -245
  116. package/hooks/gate-9.sh +0 -245
@@ -0,0 +1,452 @@
1
+ /**
2
+ * @test REQ-SASTD-E3 sastd 客户端:路径归一化、策略解析、失败绝不伪装成功
3
+ * @intent E3 把 Gate 10 接到常驻 semgrep 服务上。穿刺实测:直调 CLI 3,801-4,044ms,
4
+ * 服务热调用 2,089-2,245ms。但快路径依赖 semgrep 的内部模块
5
+ * `run_scan.run_scan_and_return_json`,官方无稳定承诺——所以这个客户端最重要的
6
+ * 性质不是"快",而是"daemon 的任何失败都必须能被上位调用方识别为不可用",
7
+ * 绝不能伪装成一次通过的扫描(#518/#559)。
8
+ * @covers AC-SASTD-01, AC-SASTD-02, AC-SASTD-03, AC-SASTD-04
9
+ */
10
+ const path = require('node:path');
11
+
12
+ const {
13
+ resolveDaemonPolicy,
14
+ normaliseResultPaths,
15
+ normalisePayload,
16
+ requestScan,
17
+ ensureDaemon,
18
+ resetDaemon,
19
+ } = require('../sastd-client');
20
+
21
+ // Assertion values, named because xp-gate-principles counts bare literals as magic
22
+ // numbers even in tests. They are deliberately meaningless: a malformed path field,
23
+ // a captured semgrep total_time, and two timeouts.
24
+ const BAD_PATH_VALUE = 42;
25
+ const CAPTURED_TOTAL_TIME = 1.98;
26
+ const SHORT_TIMEOUT_MS = 5000;
27
+ const LONG_TIMEOUT_MS = 120000;
28
+
29
+ describe('resolveDaemonPolicy — AC-SASTD-01', () => {
30
+ it('enables the daemon only for values that ask for it', () => {
31
+ for (const v of ['on', '1', 'true', 'auto', 'ON', ' On ']) {
32
+ expect(resolveDaemonPolicy({ XP_GATE_SASTD: v }).enabled).toBe(true);
33
+ }
34
+ });
35
+
36
+ it('keeps the direct path for everything else, including unset', () => {
37
+ for (const v of [undefined, '', 'off', 'direct', '0', 'false', 'bogus']) {
38
+ const env = v === undefined ? {} : { XP_GATE_SASTD: v };
39
+ expect(resolveDaemonPolicy(env).enabled).toBe(false);
40
+ }
41
+ });
42
+ });
43
+
44
+ describe('normaliseResultPaths — AC-SASTD-02', () => {
45
+ // Measured against the real CLI: this is the ONLY output difference between
46
+ // `semgrep scan --json` and the in-process API. Every other key, and every
47
+ // verdict input, is identical.
48
+ it('rewrites an absolute path to the basename the CLI would report', () => {
49
+ const out = normaliseResultPaths([{ path: path.join('C:', 'repo', 'sub', 't.js'), check_id: 'x' }]);
50
+ expect(out[0].path).toBe('t.js');
51
+ });
52
+
53
+ it('leaves an already-relative path untouched', () => {
54
+ // Rewriting this would silently drop the "sub/" prefix and make two distinct
55
+ // findings look like the same file.
56
+ const out = normaliseResultPaths([{ path: path.join('sub', 't.js') }]);
57
+ expect(out[0].path).toBe(path.join('sub', 't.js'));
58
+ });
59
+
60
+ it('preserves every other field and does not mutate the input', () => {
61
+ const original = { path: '/abs/dir/a.js', check_id: 'r', extra: { severity: 'ERROR' } };
62
+ const out = normaliseResultPaths([original]);
63
+ expect(out[0].check_id).toBe('r');
64
+ expect(out[0].extra).toEqual({ severity: 'ERROR' });
65
+ expect(original.path).toBe('/abs/dir/a.js');
66
+ });
67
+
68
+ it('tolerates malformed entries instead of throwing', () => {
69
+ expect(() => normaliseResultPaths([null, {}, { path: BAD_PATH_VALUE }])).not.toThrow();
70
+ });
71
+ });
72
+
73
+ describe('normalisePayload — AC-SASTD-03', () => {
74
+ it('normalises results and leaves the rest of the payload alone', () => {
75
+ const payload = {
76
+ results: [{ path: '/abs/x/a.js' }],
77
+ errors: [],
78
+ version: '1.183.0',
79
+ time: { rules: [], total_time: CAPTURED_TOTAL_TIME },
80
+ };
81
+ const out = normalisePayload(payload);
82
+ expect(out.results[0].path).toBe('a.js');
83
+ expect(out.version).toBe('1.183.0');
84
+ expect(out.errors).toEqual([]);
85
+ expect(out.time.total_time).toBe(CAPTURED_TOTAL_TIME);
86
+ });
87
+
88
+ it('passes through a payload with no results array', () => {
89
+ expect(normalisePayload({ version: '1' })).toEqual({ version: '1' });
90
+ expect(normalisePayload(null)).toBeNull();
91
+ });
92
+ });
93
+
94
+ describe('requestScan — AC-SASTD-04: failure must never look like success', () => {
95
+ it('reports unavailable when the interpreter does not exist', async () => {
96
+ const r = await requestScan({
97
+ config: '/nope.yml',
98
+ roots: ['/nope.js'],
99
+ pythonCmd: '/definitely/not/a/python',
100
+ timeoutMs: SHORT_TIMEOUT_MS,
101
+ });
102
+ expect(r.ok).toBe(false);
103
+ expect(typeof r.error).toBe('string');
104
+ });
105
+
106
+ it('reports unavailable when the daemon cannot import semgrep', async () => {
107
+ // A real python that cannot import semgrep: the script will raise on the
108
+ // lazy import inside the scan handler, and the reply must be ok:false.
109
+ const r = await requestScan({
110
+ config: '/nope.yml',
111
+ roots: ['/nope.js'],
112
+ pythonCmd: process.env.XP_GATE_TEST_BARE_PYTHON || 'python',
113
+ timeoutMs: LONG_TIMEOUT_MS,
114
+ });
115
+ // Either the import fails or the scan fails; both must be ok:false. What must
116
+ // NOT happen is ok:true with an empty payload being read as a clean scan.
117
+ if (!r.ok) {
118
+ expect(typeof r.error).toBe('string');
119
+ } else {
120
+ expect(r.payload).toBeDefined();
121
+ }
122
+ }, 180000);
123
+ });
124
+
125
+
126
+ describe('resident process — AC-SASTD-05: the daemon must outlive one call', () => {
127
+ // Two real bugs were written and caught here. Both produced a client that
128
+ // LOOKED correct, passed its unit tests, and delivered none of the benefit:
129
+ //
130
+ // 1. spawning a fresh python per request -- measured 4.2s, i.e. the import
131
+ // tax paid every time. The whole point of the daemon is that it does not.
132
+ // 2. registering the reader on proc.stdin instead of proc.stdout -- stdin is
133
+ // write-only, so every request sat until the 180s timeout while the daemon
134
+ // had already answered into an unread pipe.
135
+ //
136
+ // Neither is visible in the output shape; only timing and a real second call
137
+ // reveal them. Hence this test asserts on the timing of run 2+, not on run 1.
138
+
139
+ const fs = require('node:fs');
140
+ const os = require('node:os');
141
+ const { execFileSync } = require('node:child_process');
142
+
143
+ let dir;
144
+ beforeAll(() => {
145
+ dir = fs.mkdtempSync(path.join(os.tmpdir(), 'sastd-e3-'));
146
+ fs.writeFileSync(path.join(dir, 't.js'), 'eval("x");\n');
147
+ fs.writeFileSync(
148
+ path.join(dir, 'rule.yml'),
149
+ [
150
+ 'rules:',
151
+ ' - id: test-eval',
152
+ ' languages: [javascript]',
153
+ ' severity: ERROR',
154
+ ' message: eval is dangerous',
155
+ ' pattern: eval(...)',
156
+ '',
157
+ ].join('\n'),
158
+ );
159
+ });
160
+
161
+ afterAll(() => {
162
+ resetDaemon('test teardown');
163
+ try {
164
+ fs.rmSync(dir, { recursive: true, force: true });
165
+ } catch {
166
+ /* best effort */
167
+ }
168
+ });
169
+
170
+ it('the second call reuses the same daemon process', async () => {
171
+ let semgrepAvailable = true;
172
+ try {
173
+ execFileSync('python', ['-c', 'import semgrep'], { stdio: 'ignore', timeout: 120000 });
174
+ } catch {
175
+ semgrepAvailable = false;
176
+ }
177
+ if (!semgrepAvailable) {
178
+ // Skipping loudly beats a green test that proved nothing.
179
+ console.warn('[sastd] semgrep not importable in this environment; residence test skipped');
180
+ return;
181
+ }
182
+
183
+ resetDaemon('start clean');
184
+ const opts = { config: path.join(dir, 'rule.yml'), roots: [path.join(dir, 't.js')] };
185
+
186
+ const t1 = Date.now();
187
+ const first = await requestScan(opts);
188
+ const cold = Date.now() - t1;
189
+ expect(first.ok).toBe(true);
190
+
191
+ const t2 = Date.now();
192
+ const second = await requestScan(opts);
193
+ const warm = Date.now() - t2;
194
+ expect(second.ok).toBe(true);
195
+
196
+ // TIMING IS NOT THE ASSERTION. An earlier version required warm < cold - 800ms
197
+ // and flapped on a loaded machine -- this box runs at 90-100% CPU, so the noise
198
+ // routinely exceeds the effect direction. Timing also cannot distinguish "the
199
+ // daemon was reused" from "semgrep's own caches warmed up", so a genuine
200
+ // regression could hide behind it.
201
+ //
202
+ // The claim that matters is structural: the SAME process answers both calls.
203
+ // A one-spawn-per-request bug changes the identity, which no amount of machine
204
+ // load can disguise. Timing is still reported, for diagnosis only.
205
+ const a = ensureDaemon('python');
206
+ const b = ensureDaemon('python');
207
+ expect(a.ok).toBe(true);
208
+ expect(b.ok).toBe(true);
209
+ expect(b.value.proc).toBe(a.value.proc);
210
+ expect(b.value.proc.pid).toBe(a.value.proc.pid);
211
+
212
+ // Reported, not asserted: a warm call should not be dramatically slower, but
213
+ // the threshold is loose enough that load cannot fail the suite.
214
+ expect(warm).toBeLessThan(cold * 2);
215
+ }, 300000);
216
+
217
+ it('both calls return the same normalised shape, so reuse does not change output', async () => {
218
+ const opts = { config: path.join(dir, 'rule.yml'), roots: [path.join(dir, 't.js')] };
219
+ const a = await requestScan(opts);
220
+ if (!a.ok) return; // environment without semgrep: covered by the skip above
221
+ const b = await requestScan(opts);
222
+ expect(b.ok).toBe(true);
223
+
224
+ expect(a.payload.results.length).toBe(b.payload.results.length);
225
+ expect(a.payload.results[0].path).toBe(b.payload.results[0].path);
226
+ expect(path.isAbsolute(a.payload.results[0].path)).toBe(false);
227
+ expect(a.payload.results[0].extra.severity).toBe('ERROR');
228
+ }, 300000);
229
+ });
230
+
231
+
232
+ describe('process exit — AC-SASTD-06: a one-shot caller must not hang', () => {
233
+ // THE BUG THIS GUARDS AGAINST, which cost hours and was invisible to every
234
+ // existing test: a spawned child keeps the Node event loop alive. Once the client
235
+ // held a resident daemon, a caller that ran ONE scan and let Node exit naturally
236
+ // never exited at all -- the daemon lived forever, so the loop never drained.
237
+ //
238
+ // Every unit test passed, because vitest calls process.exit() itself. The real
239
+ // consumer is a shell command substitution (`X=$(node -e ...)`), which has to wait
240
+ // for node to end on its own. That is why this test spawns a real child process.
241
+ //
242
+ // Two wrong fixes were measured on the way here, and both are worse:
243
+ // - unref() at spawn: Node exited BEFORE the first scan resolved -> 0 bytes.
244
+ // - never unref: the original hang.
245
+ // The correct shape is ref-counting: hold the loop only while work is in flight.
246
+
247
+ const { execFileSync } = require('node:child_process');
248
+ const fs = require('node:fs');
249
+ const os = require('node:os');
250
+
251
+ let dir;
252
+ beforeAll(() => {
253
+ dir = fs.mkdtempSync(path.join(os.tmpdir(), 'sastd-exit-'));
254
+ fs.writeFileSync(path.join(dir, 't.js'), 'eval("x");\n');
255
+ fs.writeFileSync(
256
+ path.join(dir, 'rule.yml'),
257
+ ['rules:', ' - id: t', ' languages: [javascript]', ' severity: ERROR',
258
+ ' message: m', ' pattern: eval(...)', ''].join('\n'),
259
+ );
260
+ });
261
+
262
+ afterAll(() => {
263
+ try {
264
+ fs.rmSync(dir, { recursive: true, force: true });
265
+ } catch {
266
+ /* best effort */
267
+ }
268
+ });
269
+
270
+ it('exits on its own after a single scan (no explicit process.exit)', () => {
271
+ const script = `
272
+ const { requestScan } = require(${JSON.stringify(
273
+ path.join(__dirname, '..', 'sastd-client.js'),
274
+ )});
275
+ // NOTE: under node -e there is NO script path in argv -- argv[1] is already
276
+ // the first user argument. Indexing this as argv[2] silently passed
277
+ // undefined as the config and produced a python TypeError, which is exactly
278
+ // the trap that made the gate integration appear to fail for reasons that
279
+ // had nothing to do with the daemon.
280
+ requestScan({ config: process.argv[1], roots: [process.argv[2]] }).then((r) => {
281
+ process.stdout.write(r.ok ? 'OK:' + r.payload.results.length : 'FAIL:' + r.error);
282
+ });
283
+ `;
284
+ const start = Date.now();
285
+ let out;
286
+ try {
287
+ out = execFileSync(
288
+ process.execPath,
289
+ ['-e', script, path.join(dir, 'rule.yml'), path.join(dir, 't.js')],
290
+ { encoding: 'utf8', timeout: 60000 },
291
+ );
292
+ } catch (err) {
293
+ // A timeout here is precisely the regression: the process never exited.
294
+ throw new Error(`child did not exit cleanly: ${err.message}`);
295
+ }
296
+ const elapsed = Date.now() - start;
297
+
298
+ expect(elapsed).toBeLessThan(60000);
299
+ // Not just "it exited" -- it exited WITH the payload. An early exit would
300
+ // satisfy the timeout check while producing nothing.
301
+ expect(out.startsWith('OK:')).toBe(true);
302
+ expect(out.length).toBeGreaterThan(2);
303
+ }, 120000);
304
+ });
305
+
306
+
307
+ describe('never greener — AC-SASTD-07: a thinner scan must not read as a clean one', () => {
308
+ // The safety claim for this feature is "the daemon can make the gate slower, never
309
+ // greener". Code review is not evidence for that, so these tests drive the paths
310
+ // where a thinner result could slip through unnoticed.
311
+ //
312
+ // The dangerous shape is the VALID but EMPTY document: semgrep can return
313
+ // results: [] and errors: [] after failing to resolve a registry pack or after
314
+ // skipping every target, and gate-10 reads zero blocking findings as PASS.
315
+ // Truncated JSON needs no test here -- it fails to parse and the gate fails closed.
316
+
317
+ const { execFileSync } = require('node:child_process');
318
+ const fs = require('node:fs');
319
+ const os = require('node:os');
320
+ const pathMod = require('node:path');
321
+
322
+ const sastdDir = pathMod.resolve(__dirname, '..', '..', '..', 'sastd');
323
+ // A REAL registry pack and a SMALL directory. An earlier version used "p/x" and
324
+ // cwd: the invalid pack failed before the scan ran, so no coverage check happened
325
+ // and the test looked like a broken guard rather than a broken test.
326
+ const CONFIG = 'p/r2c-best-practices';
327
+
328
+ /** Run a snippet in a python process that has sastd importable. */
329
+ function runPython(body) {
330
+ const script = [
331
+ 'import json, sys',
332
+ 'sys.path.insert(0, sys.argv[1])',
333
+ 'import sastd',
334
+ 'CONFIG, ROOT = sys.argv[2], sys.argv[3]',
335
+ body,
336
+ ].join('\n');
337
+ const raw = execFileSync('python', ['-c', script, sastdDir, CONFIG, dir], {
338
+ encoding: 'utf8',
339
+ timeout: 120000,
340
+ });
341
+ const reply = JSON.parse(raw);
342
+ // _handle wraps a scan in {"ok": true, "data": {...}}. Unwrap so tests assert on
343
+ // the scan result itself; forgetting this layer made a working guard look broken.
344
+ return reply && reply.ok === true && reply.data ? reply.data : reply;
345
+ }
346
+
347
+ let dir;
348
+ beforeAll(() => {
349
+ dir = fs.mkdtempSync(pathMod.join(os.tmpdir(), 'sastd-green-'));
350
+ fs.writeFileSync(pathMod.join(dir, 't.js'), 'eval("x");\n');
351
+ });
352
+
353
+ afterAll(() => {
354
+ try {
355
+ fs.rmSync(dir, { recursive: true, force: true });
356
+ } catch {
357
+ /* best effort */
358
+ }
359
+ });
360
+
361
+ it('the scan HANDLER marks a scan that covered none of its roots', () => {
362
+ // Drives _handle, NOT _verify_coverage. An earlier version of this test called
363
+ // the helper directly, so deleting the helper's call site left it green: it
364
+ // proved the function worked, not that anything used it. Reverting the call in
365
+ // _handle now turns this red (verified).
366
+ const out = runPython(
367
+ [
368
+ 'import semgrep.run_scan as rs',
369
+ 'inner = rs.run_scan_and_return_json',
370
+ 'def stub(**kw):',
371
+ ' r = inner(**kw)',
372
+ ' r["results"] = []',
373
+ ' r["paths"] = {"scanned": []}',
374
+ ' return r',
375
+ 'rs.run_scan_and_return_json = stub',
376
+ 'print(json.dumps(sastd._handle({"op": "scan", "config": CONFIG, "roots": [ROOT]})))',
377
+ ].join('\n'),
378
+ );
379
+ expect((out.errors || []).map((e) => e.type)).toContain('Coverage');
380
+ }, 90000);
381
+
382
+ it('the scan HANDLER leaves a fully-covering scan untouched', () => {
383
+ // The negative half: a guard that fires on every scan would push every run onto
384
+ // the direct path and make the daemon permanently useless while looking "safe".
385
+ const out = runPython(
386
+ [
387
+ 'import semgrep.run_scan as rs',
388
+ 'inner = rs.run_scan_and_return_json',
389
+ 'def stub(**kw):',
390
+ ' r = inner(**kw)',
391
+ ' r["results"] = []',
392
+ ' r["paths"] = {"scanned": ["t.js"]}',
393
+ ' return r',
394
+ 'rs.run_scan_and_return_json = stub',
395
+ 'print(json.dumps(sastd._handle({"op": "scan", "config": CONFIG, "roots": [ROOT]})))',
396
+ ].join('\n'),
397
+ );
398
+ expect(out.errors || []).toEqual([]);
399
+ }, 90000);
400
+
401
+ it('records how many files were scanned, so a caller can compare against direct', () => {
402
+ // The daemon cannot express the CLI's --include filter, so it scans whole
403
+ // directories: a superset. Recording the count makes that checkable instead of
404
+ // assumed -- if root selection ever changed, this number would move and a
405
+ // comparison against the direct path would notice.
406
+ const out = runPython(
407
+ [
408
+ 'print(json.dumps(sastd._verify_coverage({"results": [], "errors": [], "paths": {"scanned": ["a.js", "b.js"]}}, ["."])))',
409
+ ].join('\n'),
410
+ );
411
+ expect(out.xp_gate_coverage).toEqual({ files_scanned: 2, roots_requested: 1 });
412
+ }, 90000);
413
+
414
+ it('a failing request leaves the daemon alive for the next call', () => {
415
+ // WHAT THIS DOES NOT PROVE: that double-release is impossible. I wrote a test
416
+ // for that and it passed with the guard removed, so it was proving nothing --
417
+ // the race it describes (timeout landing as a late reply arrives) needs real
418
+ // timer interleaving that a deterministic test cannot create here. Rather than
419
+ // keep a green test that cannot fail, this asserts the observable consequence
420
+ // instead, and the idempotence guard itself is justified by code review only.
421
+ //
422
+ // The consequence is checkable: a failed request must not tear down a healthy
423
+ // daemon. If a second releaseProc had unref'd the child early, the next call
424
+ // would spawn a new process and the identity below would differ.
425
+ return (async () => {
426
+ const r1 = await requestScan({ config: pathMod.join(dir, 'missing.yml'), roots: [dir], timeoutMs: 60000 });
427
+ expect(r1.ok).toBe(false);
428
+ expect(typeof r1.error).toBe('string');
429
+
430
+ const r2 = await requestScan({ config: pathMod.join(dir, 'missing.yml'), roots: [dir], timeoutMs: 60000 });
431
+ expect(r2.ok).toBe(false);
432
+
433
+ const live = ensureDaemon('python');
434
+ expect(live.ok).toBe(true);
435
+ expect(live.value.proc.killed).toBe(false);
436
+ })();
437
+ }, 180000);
438
+
439
+ it('a failed request surfaces as ok:false, never as an empty discovery', async () => {
440
+ // The client contract: there is no shape in which "the daemon did not answer"
441
+ // is expressed as "the daemon found nothing". Were this ever {ok:true,
442
+ // payload:{results:[]}}, the gate would report PASS on a dead daemon.
443
+ const r = await requestScan({
444
+ config: pathMod.join(dir, 'no-such-rules.yml'),
445
+ roots: [pathMod.join(dir, 't.js')],
446
+ timeoutMs: 60000,
447
+ });
448
+ expect(r.ok).toBe(false);
449
+ expect(typeof r.error).toBe('string');
450
+ expect(r.payload).toBeUndefined();
451
+ }, 120000);
452
+ });
@@ -0,0 +1,69 @@
1
+ /**
2
+ * @test REQ-DEPLOY-001 copyHooks 消费方接线(AC-DEPLOY-08/09)
3
+ * @intent 验证 shared-utils.copyHooks 与 update-hooks.copyHooks 的 hook 文件列表
4
+ * 来自 deploy-manifest.js 的单一事实源(HOOK_FILES),而非各自手写的字面量
5
+ * 清单。update-hooks 原先只拷 3 个 hook(pre-commit/pre-push/post-merge),
6
+ * 缺 post-commit 与 hook-module-resolution.sh——后者缺失会让 pre-commit 在
7
+ * 任何 tier 决策前 fail-closed FATAL,即 AC-DEPLOY-09 记录的活 bug。
8
+ * 接线后两者都从 HOOK_FILES 取,update-hooks 自动补齐 5 个。
9
+ * @covers AC-DEPLOY-08, AC-DEPLOY-09
10
+ */
11
+ const fs = require('node:fs');
12
+ const os = require('node:os');
13
+ const path = require('node:path');
14
+
15
+ const manifest = require('../deploy-manifest.js');
16
+ const updateHooks = require('../update-hooks.js');
17
+
18
+ const LIB_DIR = path.resolve(__dirname, '..');
19
+ const SHARED_UTILS = path.join(LIB_DIR, 'shared-utils.js');
20
+ const UPDATE_HOOKS = path.join(LIB_DIR, 'update-hooks.js');
21
+ const PKG_ROOT = path.resolve(LIB_DIR, '..');
22
+
23
+ describe('copyHooks consumers wire to deploy-manifest (REQ-DEPLOY-001)', () => {
24
+ describe('AC-DEPLOY-08: 数据源统一,无私有清单', () => {
25
+ it('shared-utils.js 从 deploy-manifest 取 hook 列表', () => {
26
+ const src = fs.readFileSync(SHARED_UTILS, 'utf8');
27
+ expect(src).toMatch(/require\(['"]\.\/deploy-manifest\.js['"]\)/);
28
+ // 反空缺:硬编码字面量必须消失,否则"消费清单"只是注释里的一句话。
29
+ expect(src).not.toMatch(/\['pre-commit'\s*,\s*'pre-push'/);
30
+ });
31
+
32
+ it('update-hooks.js 从 deploy-manifest 取 hook 列表', () => {
33
+ const src = fs.readFileSync(UPDATE_HOOKS, 'utf8');
34
+ expect(src).toMatch(/require\(['"]\.\/deploy-manifest\.js['"]\)/);
35
+ expect(src).not.toMatch(/\['pre-commit'\s*,\s*'pre-push'\s*,\s*'post-merge'\]/);
36
+ });
37
+
38
+ it('init.js 已经由 shared-utils.copyHooks 间接消费(无需自持清单)', () => {
39
+ const src = fs.readFileSync(path.join(LIB_DIR, 'init.js'), 'utf8');
40
+ expect(src).toMatch(/require\(['"]\.\/shared-utils\.js['"]\)/);
41
+ expect(src).toMatch(/copyHooks/);
42
+ });
43
+ });
44
+
45
+ describe('AC-DEPLOY-09: update-hooks 装出 HOOK_FILES 全集', () => {
46
+ it('update-hooks.copyHooks 拷出 5 个 hook 与 lib/', () => {
47
+ const destDir = fs.mkdtempSync(path.join(os.tmpdir(), 'xp-gate-ac09-'));
48
+ try {
49
+ updateHooks.copyHooks(PKG_ROOT, destDir, false, false);
50
+
51
+ for (const hook of manifest.HOOK_FILES) {
52
+ expect(
53
+ fs.existsSync(path.join(destDir, hook)),
54
+ `update-hooks 未部署 ${hook}——缺 hook-module-resolution.sh 会让 pre-commit FATAL`,
55
+ ).toBe(true);
56
+ }
57
+ // 反空缺:hook 集必须恰好是 HOOK_FILES 的规模,不是"至少 3 个"。
58
+ const shipped = fs
59
+ .readdirSync(destDir, { withFileTypes: true })
60
+ .filter(e => e.isFile() && manifest.HOOK_FILES.includes(e.name))
61
+ .map(e => e.name);
62
+ expect(shipped.sort()).toEqual([...manifest.HOOK_FILES].sort());
63
+ expect(fs.existsSync(path.join(destDir, 'lib'))).toBe(true);
64
+ } finally {
65
+ fs.rmSync(destDir, { recursive: true, force: true });
66
+ }
67
+ });
68
+ });
69
+ });
@@ -62,6 +62,7 @@ function repoTemplate() {
62
62
  if (_repoTemplate) return _repoTemplate;
63
63
  const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'rework-template-'));
64
64
  git('init', dir);
65
+ git('config core.hooksPath /dev/null', dir);
65
66
  git('config user.email "test@test.com"', dir);
66
67
  git('config user.name "Test"', dir);
67
68
  _repoTemplate = dir;
@@ -0,0 +1,87 @@
1
+ /**
2
+ * arch-config-template.js — 项目级默认架构配置的单一来源(REQ-DEPLOY-003)
3
+ *
4
+ * WHY THIS FILE EXISTS
5
+ * --------------------
6
+ * Gate 6 自 2026-05-04 起对「没有架构配置文件」的项目直接阻塞提交
7
+ * (`githooks/pre-commit:4838` 逐字输出 `❌ ARCHITECTURE CONFIG MISSING - COMMIT BLOCKED`)。
8
+ * 实测该判定是纯文件存在性检查:
9
+ *
10
+ * [ -f "$PROJECT_ROOT/architecture.yaml" ] || [ -f "$PROJECT_ROOT/.architecturerc" ] \
11
+ * || [ -f "$PROJECT_ROOT/.archlint.yaml" ]
12
+ *
13
+ * 它**从不解析内容**。于是 `xp-gate init` 装好了全部 gate,用户第一次 commit 却被
14
+ * 拦住,原因与代码质量无关——只是因为少一个文件。这就是本模块要消除的失败模式:
15
+ * 安装成功的产品在新项目里不可用。
16
+ *
17
+ * WHY THE CONTENT CONTAINS ZERO CONFIGURATION KEYS
18
+ * -----------------------------------------------
19
+ * 实测(设计文档 §3.4 实验 D/E):
20
+ * - 在 archlint 0.16.0 下写 `ignore: ["src/b.ts"]`,`files_analyzed` 仍是 2、
21
+ * `cyclic_dependencies` 仍是 1 —— **该键被静默忽略**。
22
+ * - 只含注释的配置文件与"没有配置文件"行为完全一致。
23
+ *
24
+ * 所以生成一份写了规则的配置,会让用户看到「已配置架构约束」而实际什么都没约束。
25
+ * 那比没有文件更糟:没有文件至少是诚实的。本模板因此**只写注释**,它的价值全部
26
+ * 来自三件事:
27
+ * 1. 让 Gate 6 的存在性前置条件成立(这是它的唯一功能作用);
28
+ * 2. 承载说明:为什么是空的、怎么验证、想要真配置时该看什么;
29
+ * 3. 给用户一个将来可以往里加东西的地方。
30
+ *
31
+ * GLOBAL INSTALL MUST NOT WRITE THIS
32
+ * ----------------------------------
33
+ * 用户决策(sprint-20261110-33):默认架构配置只在**项目级** init 生成。
34
+ * 全局安装写用户 HOME 会让一份项目相关的文件变成机器级副作用。
35
+ * 本模块因此不引用 HOME / homedir,写入由 init.js 的 installLocal 路径负责。
36
+ */
37
+ 'use strict';
38
+
39
+ /** 生成的文件名。与 pre-commit 的三个存在性判定之一逐字对应。 */
40
+ const CONFIG_FILENAME = '.archlint.yaml';
41
+
42
+ /**
43
+ * 生成内容。只有一个作用:让 Gate 6 的存在性检查通过,并把这件事说清楚。
44
+ *
45
+ * 新增这里的文案时注意:它是**新增文案契约**(约束我们自己产出什么),
46
+ * 不是对既有输出的观测。测试从本常量读取,不重写字面量——两处各写一份
47
+ * 迟早会漂移,而漂移后测试仍然为真。
48
+ */
49
+ const ARCH_CONFIG_TEMPLATE = `# Architecture lint configuration for Gate 6.
50
+ #
51
+ # This file deliberately contains no configuration keys.
52
+ #
53
+ # WHY IT IS EMPTY
54
+ # Gate 6 blocks a commit when no architecture config file exists — it checks
55
+ # for the file's existence only and never parses what is inside:
56
+ #
57
+ # [ -f architecture.yaml ] || [ -f .architecturerc ] || [ -f .archlint.yaml ]
58
+ #
59
+ # So this file's job is to satisfy that precondition, nothing more. It is
60
+ # generated by 'xp-gate init' so a freshly set-up project can commit.
61
+ #
62
+ # WHY THERE ARE NO RULES HERE
63
+ # Writing rules that the tool silently ignores would be worse than an empty
64
+ # file: the file would look configured while constraining nothing. Verified
65
+ # against archlint 0.16.0 that keys such as 'ignore:' and 'rules:' have no
66
+ # effect on the analysis, so none are written.
67
+ #
68
+ # WHAT ACTUALLY RUNS
69
+ # With no keys set, archlint's own default detectors apply. To see exactly
70
+ # which detectors are active:
71
+ #
72
+ # archlint detectors list
73
+ #
74
+ # HOW TO CONFIGURE FOR REAL
75
+ # Add keys below once you have confirmed they take effect for your installed
76
+ # archlint version. Check the difference in the report before and after:
77
+ #
78
+ # archlint -f json . | head -40
79
+ #
80
+ # Delete this file and Gate 6 will block commits again until another config
81
+ # file (architecture.yaml or .architecturerc) is present.
82
+ `;
83
+
84
+ module.exports = Object.freeze({
85
+ CONFIG_FILENAME,
86
+ ARCH_CONFIG_TEMPLATE,
87
+ });