@boyingliu01/xp-gate 0.37.3 → 0.38.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 (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 +514 -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 +572 -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,572 @@
1
+ /**
2
+ * Client for the xp-gate SAST daemon.
3
+ *
4
+ * The daemon keeps one semgrep process alive so its ~1.3s import cost is paid
5
+ * once instead of once per gate run. This module is the only thing that talks to
6
+ * it, and it is deliberately paranoid: EVERY failure mode here resolves to
7
+ * "unavailable", which the caller turns into a direct scan. A daemon that cannot
8
+ * answer must never be allowed to look like a gate that passed.
9
+ *
10
+ * Measured on this machine (1 local rule, 1 file):
11
+ * direct semgrep scan : 3,801-4,044 ms
12
+ * daemon, hot call : 2,089-2,245 ms
13
+ */
14
+ 'use strict';
15
+
16
+ const { spawn } = require('node:child_process');
17
+ const path = require('node:path');
18
+
19
+ /** Gate 10's own timeout default, mirrored: a daemon call may not outlive it. */
20
+ const DEFAULT_TIMEOUT_MS = 180_000;
21
+
22
+ /**
23
+ * Decide whether the daemon should even be attempted for this invocation.
24
+ *
25
+ * Returns { enabled: false, reason } for anything that is not an explicit "on".
26
+ * `auto` is deliberately NOT treated as degraded by the caller -- see
27
+ * gate-10.sh -- but it does still mean "try the daemon if one exists".
28
+ *
29
+ * @param {Record<string, string|undefined>} env
30
+ * @returns {{enabled: boolean, reason: string}}
31
+ */
32
+ function resolveDaemonPolicy(env = process.env) {
33
+ const raw = (env.XP_GATE_SASTD || 'direct').trim().toLowerCase();
34
+ if (raw === 'on' || raw === '1' || raw === 'true' || raw === 'auto') {
35
+ return { enabled: true, reason: 'requested' };
36
+ }
37
+ return { enabled: false, reason: 'not_requested' };
38
+ }
39
+
40
+ /**
41
+ * True when <p> is absolute in EITHER POSIX or Windows form.
42
+ *
43
+ * `path.isAbsolute` answers for the HOST platform only, which is the wrong
44
+ * question here: a scan's paths come from whichever machine semgrep ran on, and
45
+ * they cross a process boundary (the daemon) and sometimes a platform boundary
46
+ * (a reported path can be pasted between OSes). On Linux, `C:/repo/t.js` is not
47
+ * absolute, so the old check left it as-is and the report kept a full path --
48
+ * the exact "suddenly absolute path looks like a different finding" problem
49
+ * this function exists to prevent (#SASTD-02).
50
+ *
51
+ * @param {string} p
52
+ * @returns {boolean}
53
+ */
54
+ function isAnyAbsolute(p) {
55
+ if (path.isAbsolute(p)) return true;
56
+ // Windows drive-absolute: "C:\x" or "C:/x".
57
+ if (/^[A-Za-z]:[\\/]/.test(p)) return true;
58
+ // Windows UNC: "\\server\share" or the forward-slash form of it.
59
+ return /^[\\/]{2}[^\\/]/.test(p);
60
+ }
61
+
62
+ /**
63
+ * Basename of <p> under either path convention.
64
+ *
65
+ * `path.basename` is host-dependent too: on POSIX, `path.basename('C:/a/b.js')`
66
+ * returns `'b.js'` only by luck (the last separator happens to be '/'), while
67
+ * `path.basename('C:\\a\\b.js')` returns the whole string. Splitting on both
68
+ * separators is what makes the result the same whichever host runs it.
69
+ *
70
+ * @param {string} p
71
+ * @returns {string}
72
+ */
73
+ function anyBasename(p) {
74
+ const parts = p.split(/[\\/]+/).filter((s) => s.length > 0);
75
+ return parts.length > 0 ? parts[parts.length - 1] : p;
76
+ }
77
+
78
+ /**
79
+ * Normalise one semgrep result so the daemon's output matches the CLI's.
80
+ *
81
+ * Measured difference (verified byte-for-byte against `semgrep scan --json`):
82
+ * the CLI reports repo-relative paths ("t.js") while the in-process API reports
83
+ * absolute ones ("C:\...\t.js"). Everything else -- every top-level key, every
84
+ * result field, and the verdict inputs (extra.severity, result count) -- is
85
+ * identical.
86
+ *
87
+ * The verdict logic in gate-10.sh reads only `extra.severity` and the counts, so
88
+ * this difference cannot change a PASS/FAIL. It is fixed anyway because the
89
+ * report prints the path, and a suddenly-absolute path would look like a
90
+ * different finding to anyone reading it or diffing two runs.
91
+ *
92
+ * Basename is used rather than a repo-relative computation: gate-10 already
93
+ * passes one directory per staged file and the CLI's own "relative" path is the
94
+ * basename for those targets, confirmed equal on the same fixture.
95
+ *
96
+ * @param {Array<Record<string, unknown>>} results
97
+ * @returns {Array<Record<string, unknown>>}
98
+ */
99
+ function normaliseResultPaths(results) {
100
+ if (!Array.isArray(results)) return results;
101
+ return results.map((r) => {
102
+ if (!r || typeof r.path !== 'string') return r;
103
+ // Only rewrite absolute paths. A relative path is already what we want, and
104
+ // basename-ing it would silently destroy a subdirectory prefix.
105
+ if (!isAnyAbsolute(r.path)) return r;
106
+ return { ...r, path: anyBasename(r.path) };
107
+ });
108
+ }
109
+
110
+ /**
111
+ * Apply the same normalisation to a whole semgrep payload.
112
+ *
113
+ * @param {Record<string, any>} payload
114
+ * @returns {Record<string, any>}
115
+ */
116
+ function normalisePayload(payload) {
117
+ if (!payload || typeof payload !== 'object') return payload;
118
+ if (!Array.isArray(payload.results)) return payload;
119
+ return { ...payload, results: normaliseResultPaths(payload.results) };
120
+ }
121
+
122
+ /**
123
+ * Parse NDJSON from a stream and resolve the first complete line.
124
+ *
125
+ * @param {import('node:stream').Readable} stream
126
+ * @param {number} timeoutMs
127
+ * @returns {Promise<string>}
128
+ */
129
+ function readLine(stream, timeoutMs) {
130
+ return new Promise((resolve, reject) => {
131
+ let buffer = '';
132
+ let done = false;
133
+
134
+ const finish = (fn, value) => {
135
+ if (done) return;
136
+ done = true;
137
+ clearTimeout(timer);
138
+ stream.removeListener('data', onData);
139
+ stream.removeListener('error', onError);
140
+ stream.removeListener('end', onEnd);
141
+ fn(value);
142
+ };
143
+
144
+ const onData = (chunk) => {
145
+ buffer += chunk.toString();
146
+ const nl = buffer.indexOf('\n');
147
+ if (nl >= 0) finish(resolve, buffer.slice(0, nl));
148
+ };
149
+ const onError = (err) => finish(reject, err);
150
+ const onEnd = () => finish(reject, new Error('daemon closed the stream without replying'));
151
+
152
+ const timer = setTimeout(
153
+ () => finish(reject, new Error(`daemon did not reply within ${timeoutMs}ms`)),
154
+ timeoutMs,
155
+ );
156
+ timer.unref?.();
157
+
158
+ stream.on('data', onData);
159
+ stream.on('error', onError);
160
+ stream.on('end', onEnd);
161
+ });
162
+ }
163
+
164
+ /** The resident daemon, or null when it is not running. Module-level on purpose:
165
+ * the process has to survive this function returning, which is the entire point. */
166
+ let activeDaemon = null;
167
+
168
+ /** Idle deadline: after this long with no request, let the daemon exit so it
169
+ * stops holding ~200MB of semgrep in RAM between commits. */
170
+ const IDLE_TIMEOUT_MS = 30 * 60 * 1000;
171
+
172
+ /** How many stderr lines to keep for diagnosis. Enough to see a traceback's tail. */
173
+ const STDERR_TAIL_LINES = 50;
174
+
175
+ /**
176
+ * Start the daemon if it is not already running.
177
+ *
178
+ * @param {string} pythonCmd
179
+ * @returns {{ok: true, value: object} | {ok: false, error: string}}
180
+ */
181
+ function ensureDaemon(pythonCmd) {
182
+ if (isDaemonAlive()) {
183
+ if (activeDaemon.idleTimer) activeDaemon.idleTimer.refresh();
184
+ return { ok: true, value: activeDaemon };
185
+ }
186
+
187
+ const spawned = spawnDaemon(pythonCmd);
188
+ if (!spawned.ok) return spawned;
189
+ const { proc, getSpawnError } = spawned.value;
190
+
191
+ attachLifecycle(proc);
192
+
193
+ // Start unref'd so an idle daemon cannot pin the process open. exchange() refs it
194
+ // for the duration of each request -- see refProc/releaseProc for why neither
195
+ // "always ref" nor "always unref" works.
196
+ proc.unref?.();
197
+ proc.stdin?.unref?.();
198
+ proc.stdout?.unref?.();
199
+ proc.stderr?.unref?.();
200
+
201
+ const idleTimer = startIdleTimer();
202
+ installExitHook();
203
+
204
+ activeDaemon = {
205
+ proc,
206
+ // stdout, NOT stdin: stdin is write-only, so a 'data' listener there never fires
207
+ // and every request would sit until the timeout with the answer unread.
208
+ socket: proc.stdout,
209
+ pending: 0,
210
+ idleTimer,
211
+ getSpawnError,
212
+ stderrTail: drainStderr(proc),
213
+ };
214
+ return { ok: true, value: activeDaemon };
215
+ }
216
+
217
+ /** True when a daemon is running and still usable. */
218
+ function isDaemonAlive() {
219
+ return Boolean(activeDaemon) && !activeDaemon.proc.killed && activeDaemon.proc.exitCode === null;
220
+ }
221
+
222
+ /**
223
+ * Spawn the daemon process and wire its error reporting.
224
+ *
225
+ * @param {string} pythonCmd
226
+ * @returns {{ok: true, value: object} | {ok: false, error: string}}
227
+ */
228
+ function spawnDaemon(pythonCmd) {
229
+ const daemonPath = path.join(__dirname, '..', '..', 'sastd', 'sastd.py');
230
+ let proc;
231
+ try {
232
+ proc = spawn(pythonCmd, [daemonPath], { stdio: ['pipe', 'pipe', 'pipe'], windowsHide: true });
233
+ } catch (err) {
234
+ return { ok: false, error: `spawn failed: ${err.message}` };
235
+ }
236
+
237
+ // spawn() reports a missing interpreter as an asynchronous 'error' event, not a
238
+ // throw. Unhandled, that event takes down the whole process -- observed as vitest
239
+ // reporting "Errors 1" while every assertion passed.
240
+ let spawnError = null;
241
+ proc.on('error', (err) => {
242
+ spawnError = err;
243
+ activeDaemon = null;
244
+ });
245
+
246
+ // A broken pipe on the request stream is reported as an 'error' event, asynchronously.
247
+ // Node tolerates EPIPE on a child's stdin (verified: writing after the child exited
248
+ // does not throw and does not crash), so this is defence rather than a known crash.
249
+ // It is here because the alternative -- if that tolerance ever changed -- is an
250
+ // unhandled event taking down the whole gate, and losing the daemon must never be
251
+ // worse than not having one.
252
+ proc.stdin?.on('error', (err) => {
253
+ spawnError = err;
254
+ resetDaemon(`stdin error: ${err.message}`);
255
+ });
256
+
257
+ return { ok: true, value: { proc, getSpawnError: () => spawnError } };
258
+ }
259
+
260
+ /**
261
+ * Forget the daemon when it dies, so the next call restarts instead of writing
262
+ * into a dead pipe and reporting a timeout that hides the real cause.
263
+ *
264
+ * @param {import('node:child_process').ChildProcess} proc
265
+ */
266
+ function attachLifecycle(proc) {
267
+ proc.on('exit', () => {
268
+ if (activeDaemon && activeDaemon.proc === proc) activeDaemon = null;
269
+ });
270
+ }
271
+
272
+ /**
273
+ * Drain stderr so the child never blocks on a full pipe. semgrep is chatty, and
274
+ * a blocked child looks exactly like a hung scan.
275
+ *
276
+ * @param {import('node:child_process').ChildProcess} proc
277
+ * @returns {string[]} rolling tail, newest last
278
+ */
279
+ function drainStderr(proc) {
280
+ const tail = [];
281
+ proc.stderr.on('data', (chunk) => {
282
+ tail.push(chunk.toString());
283
+ if (tail.length > STDERR_TAIL_LINES) tail.shift();
284
+ });
285
+ return tail;
286
+ }
287
+
288
+ /**
289
+ * Make sure the daemon does not outlive the Node process that started it.
290
+ *
291
+ * WHY THIS IS NEEDED: a spawned child keeps the event loop alive, so a script that
292
+ * runs one scan and lets Node exit naturally would hang forever -- the daemon never
293
+ * ends, the loop never empties. Measured as a shell command substitution
294
+ * (`X=$(node -e ...)`) that never returned.
295
+ *
296
+ * WHY NOT unref(): unref drops the keep-alive immediately, and Node then exits
297
+ * BEFORE the in-flight scan resolves -- measured as 0 bytes of output where a full
298
+ * payload was expected. The keep-alive has to last exactly as long as the work, so
299
+ * the hook fires at 'beforeExit', after pending work is done.
300
+ */
301
+ let exitHookInstalled = false;
302
+
303
+ function installExitHook() {
304
+ if (exitHookInstalled) return;
305
+ exitHookInstalled = true;
306
+
307
+ // 'exit' is the only event that does not depend on the loop draining -- and the
308
+ // loop cannot drain while the child is alive, so 'beforeExit' deadlocks here
309
+ // (measured: still hanging with the beforeExit hook in place).
310
+ process.once('exit', () => resetDaemon('process exiting'));
311
+
312
+ // Belt and braces for the case where the caller never lets the loop drain:
313
+ // 'exit' does not fire until something else ends the process, so also drop the
314
+ // keep-alive whenever the loop reports it is idle. `beforeExit` is re-emitted
315
+ // every time the loop empties, so the final one sees a daemon with no pending
316
+ // work and releases it.
317
+ // The real release point: the moment a request settles, if nothing is queued,
318
+ // the child stops being allowed to hold the process open. This preserves the
319
+ // benefit for a long-lived caller (repeated requestScan calls reuse the warm
320
+ // daemon) while letting a one-shot caller exit normally.
321
+ process.on('beforeExit', () => {
322
+ if (activeDaemon && activeDaemon.pending === 0) {
323
+ releaseKeepAlive();
324
+ }
325
+ });
326
+ process.once('exit', () => {
327
+ if (activeDaemon) resetDaemon('process exiting');
328
+ });
329
+ }
330
+
331
+ /**
332
+ * Let Node exit without killing the daemon's usefulness immediately.
333
+ *
334
+ * unref() at SPAWN time was wrong (Node exited before the first scan resolved).
335
+ * unref() here is right: the work is done, so the child may no longer pin the loop.
336
+ * The daemon process itself keeps running until it is killed or goes idle, so a
337
+ * subsequent call in the same process still reuses it -- but a one-shot caller is
338
+ * no longer prevented from exiting.
339
+ */
340
+ function releaseKeepAlive() {
341
+ if (!activeDaemon || activeDaemon.keepAliveReleased) return;
342
+ activeDaemon.keepAliveReleased = true;
343
+ activeDaemon.proc.unref();
344
+ activeDaemon.proc.stdin?.unref?.();
345
+ activeDaemon.proc.stdout?.unref?.();
346
+ activeDaemon.proc.stderr?.unref?.();
347
+ }
348
+
349
+ /**
350
+ * Ref-count the daemon child around one request.
351
+ *
352
+ * unref() at spawn time was wrong (Node exited before the first scan resolved --
353
+ * 0 bytes of output). Never unref'ing was also wrong (a one-shot caller never
354
+ * exited; measured as a shell command substitution that hung forever). Holding only
355
+ * while work is in flight satisfies both.
356
+ */
357
+ let inFlight = 0;
358
+
359
+ function refProc(proc) {
360
+ inFlight += 1;
361
+ proc.ref?.();
362
+ proc.stdin?.ref?.();
363
+ proc.stdout?.ref?.();
364
+ proc.stderr?.ref?.();
365
+ }
366
+
367
+ function releaseProc(proc) {
368
+ inFlight = Math.max(0, inFlight - 1);
369
+ if (inFlight > 0) return;
370
+ proc.unref?.();
371
+ proc.stdin?.unref?.();
372
+ proc.stdout?.unref?.();
373
+ proc.stderr?.unref?.();
374
+ }
375
+
376
+ /** Let the daemon exit after a quiet spell so it stops holding semgrep in RAM. */
377
+ function startIdleTimer() {
378
+ const timer = setTimeout(() => resetDaemon('idle'), IDLE_TIMEOUT_MS);
379
+ timer.unref?.();
380
+ return timer;
381
+ }
382
+
383
+ /**
384
+ * Forget and stop the daemon. Safe to call when none is running.
385
+ *
386
+ * @param {string} reason recorded on the object only; kept for debuggability
387
+ */
388
+ function resetDaemon(reason) {
389
+ if (!activeDaemon) return;
390
+ const { proc, idleTimer } = activeDaemon;
391
+ activeDaemon = null;
392
+ try {
393
+ clearTimeout(idleTimer);
394
+ } catch {
395
+ /* already cleared */
396
+ }
397
+ try {
398
+ proc.stdin.end();
399
+ } catch {
400
+ /* already gone */
401
+ }
402
+ try {
403
+ proc.kill();
404
+ } catch {
405
+ /* already gone */
406
+ }
407
+ // reason is intentionally not thrown or logged here: callers report their own
408
+ // error, and a daemon restart is a normal, non-exceptional event.
409
+ void reason;
410
+ }
411
+
412
+ /**
413
+ * Read one NDJSON line from a socket, with a timeout.
414
+ *
415
+ * @param {import('node:net').Socket} socket
416
+ * @param {(line: string|null, err: Error|null) => void} cb
417
+ * @param {number} timeoutMs
418
+ */
419
+ function readOneLine(socket, cb, timeoutMs) {
420
+ let buffer = '';
421
+ let settled = false;
422
+
423
+ const done = (line, err) => {
424
+ if (settled) return;
425
+ settled = true;
426
+ clearTimeout(timer);
427
+ socket.removeListener('data', onData);
428
+ socket.removeListener('error', onError);
429
+ socket.removeListener('close', onClose);
430
+ cb(line, err);
431
+ };
432
+
433
+ const onData = (chunk) => {
434
+ buffer += chunk.toString();
435
+ const nl = buffer.indexOf('\n');
436
+ if (nl >= 0) done(buffer.slice(0, nl), null);
437
+ };
438
+ const onError = (err) => done(null, err);
439
+ const onClose = () => done(null, new Error('daemon closed the connection without replying'));
440
+ const timer = setTimeout(() => done(null, new Error(`daemon did not reply within ${timeoutMs}ms`)), timeoutMs);
441
+ timer.unref?.();
442
+
443
+ socket.on('data', onData);
444
+ socket.on('error', onError);
445
+ socket.on('close', onClose);
446
+ }
447
+
448
+ /**
449
+ * Ask the resident daemon to scan, starting it on first use.
450
+ *
451
+ * THE WHOLE POINT IS THAT THE PROCESS OUTLIVES ONE CALL. An earlier version of
452
+ * this function spawned a fresh python per request; measured, that cost ~4.2s --
453
+ * i.e. it paid semgrep's import tax every time and delivered none of the benefit.
454
+ * A resident process answers in ~2.1s after the first call. So the client connects
455
+ * to a long-lived child, keeps it, and only restarts when it dies or goes idle.
456
+ *
457
+ * Never throws. Every failure -- spawn failed, import broken, internal API
458
+ * renamed, timeout, malformed reply, daemon died mid-request -- resolves to
459
+ * `{ok:false}` so the caller falls back to a real direct scan. The daemon can make
460
+ * the gate slower; it must never make it greener (#518/#559).
461
+ *
462
+ * @param {{config: string, roots: string[], pythonCmd?: string, timeoutMs?: number}} opts
463
+ * @returns {Promise<{ok: true, payload: object} | {ok: false, error: string}>}
464
+ */
465
+ async function requestScan(opts) {
466
+ const {
467
+ config,
468
+ roots,
469
+ pythonCmd = process.env.XP_GATE_SASTD_PYTHON || 'python',
470
+ timeoutMs = DEFAULT_TIMEOUT_MS,
471
+ } = opts;
472
+
473
+ let conn;
474
+ try {
475
+ conn = ensureDaemon(pythonCmd);
476
+ } catch (err) {
477
+ return { ok: false, error: `spawn failed: ${err.message}` };
478
+ }
479
+ if (!conn.ok) return conn;
480
+
481
+ return exchange(conn.value, { op: 'scan', config, roots }, timeoutMs);
482
+ }
483
+
484
+ /**
485
+ * Send one request to a live daemon and turn its reply into a result.
486
+ *
487
+ * @param {object} daemon
488
+ * @param {Record<string, unknown>} request
489
+ * @param {number} timeoutMs
490
+ * @returns {Promise<{ok: true, payload: object} | {ok: false, error: string}>}
491
+ */
492
+ function exchange(daemon, request, timeoutMs) {
493
+ return new Promise((resolve) => {
494
+ const { socket, proc } = daemon;
495
+
496
+ // Hold the process open for the duration of the request only. Without this,
497
+ // Node can exit mid-scan (measured: 0 bytes of output); with a permanent hold,
498
+ // a one-shot caller never exits at all. Ref-counting per request gives both:
499
+ // work in flight keeps the loop alive, and an idle daemon does not.
500
+ refProc(proc);
501
+
502
+ // Tag this request so a reply arriving for a prior, timed-out request cannot
503
+ // be mistaken for this one's answer. Without it, one slow scan poisons the
504
+ // next verdict -- exactly the failure a security gate must not have.
505
+ daemon.pending += 1;
506
+ const sequence = daemon.pending;
507
+
508
+ // Exactly one release per request. finish() is reachable from three paths -- the
509
+ // reply, the outer timeout, and the write failure -- and more than one can fire
510
+ // (a timeout landing while a late reply arrives; a write failure racing the read
511
+ // timer). A second releaseProc decrements inFlight below the real number of live
512
+ // requests and unrefs a process still in use, letting Node exit mid-scan.
513
+ let released = false;
514
+ let timer = null;
515
+ const finish = (result) => {
516
+ if (released) return;
517
+ released = true;
518
+ clearTimeout(timer);
519
+ releaseProc(proc);
520
+ resolve(result);
521
+ };
522
+
523
+ timer = setTimeout(() => {
524
+ finish({ ok: false, error: `daemon did not reply within ${timeoutMs}ms` });
525
+ // A daemon that missed its deadline may be wedged; do not keep feeding it.
526
+ resetDaemon(`timeout on request ${sequence}`);
527
+ }, timeoutMs);
528
+ timer.unref?.();
529
+
530
+ readOneLine(socket, (line, err) => finish(interpretReply(line, err)), timeoutMs);
531
+
532
+ try {
533
+ proc.stdin.write(JSON.stringify(request) + '\n');
534
+ } catch (writeErr) {
535
+ resetDaemon(`write failed: ${writeErr.message}`);
536
+ finish({ ok: false, error: `write failed: ${writeErr.message}` });
537
+ }
538
+ });
539
+ }
540
+
541
+ /**
542
+ * Turn a raw line (or transport error) into the result the caller sees.
543
+ *
544
+ * @param {string|null} line
545
+ * @param {Error|null} err
546
+ * @returns {{ok: true, payload: object} | {ok: false, error: string}}
547
+ */
548
+ function interpretReply(line, err) {
549
+ if (err) return { ok: false, error: err.message };
550
+ let reply;
551
+ try {
552
+ reply = JSON.parse(line);
553
+ } catch {
554
+ return { ok: false, error: `malformed reply: ${String(line).slice(0, 120)}` };
555
+ }
556
+ if (!reply || reply.ok !== true) {
557
+ // The daemon answered and said no. Keep it alive: a bad config is the
558
+ // caller's problem, not a reason to tear down a healthy process.
559
+ return { ok: false, error: reply?.error || 'daemon reported failure' };
560
+ }
561
+ return { ok: true, payload: normalisePayload(reply.data) };
562
+ }
563
+
564
+ module.exports = {
565
+ resolveDaemonPolicy,
566
+ normaliseResultPaths,
567
+ normalisePayload,
568
+ requestScan,
569
+ ensureDaemon,
570
+ resetDaemon,
571
+ DEFAULT_TIMEOUT_MS,
572
+ };
@@ -67,7 +67,10 @@ function copyHooks(srcDir, destDir) {
67
67
  // hook-module-resolution.sh (#655/#631) is loaded by pre-commit BEFORE any tier
68
68
  // decision and fails closed — omitting it made every commit FATAL on a fresh
69
69
  // install. It is generated, but it must still ship beside the hooks.
70
- const hookFiles = ['pre-commit', 'pre-push', 'post-commit', 'post-merge', 'hook-module-resolution.sh'];
70
+ // REQ-DEPLOY-001: the list comes from the single deploy-manifest module. A
71
+ // hand-kept copy here was one of four divergent ones (#789 root cause ②), and
72
+ // it is exactly how post-commit silently stopped being installed before.
73
+ const hookFiles = require('./deploy-manifest.js').HOOK_FILES;
71
74
  hookFiles.forEach(hook => {
72
75
  const src = path.join(srcDir, 'hooks', hook);
73
76
  const dest = path.join(destDir, hook);
@@ -77,19 +80,38 @@ function copyHooks(srcDir, destDir) {
77
80
  }
78
81
  });
79
82
 
80
- // Copy lib/ directory (e.g. now-ms.sh) — sourced by pre-commit at runtime
81
- const libSrc = path.join(srcDir, 'hooks', 'lib');
82
- const libDest = path.join(destDir, 'lib');
83
- if (fs.existsSync(libSrc)) {
84
- copyDirRecursive(libSrc, libDest);
85
- }
83
+ // Copy the non-hook modules (lib/*.sh, lib/*.cjs, lib/*.py, lib/*.ps1,
84
+ // adapter-common.sh, deploy-manifest.sh, install.sh) from the manifest.
85
+ //
86
+ // REQ-DEPLOY-002: this used to be `copyDirRecursive(path.join(srcDir,'hooks','lib'))`
87
+ // — a hardcoded directory copy that bypassed the manifest entirely. Two problems,
88
+ // and the second is worse than the first:
89
+ // 1. adapter-common.sh, deploy-manifest.sh and install.sh were never installed,
90
+ // because they are not under lib/ and HOOK_FILES did not list them.
91
+ // 2. Copying an entire directory means the manifest cannot describe what gets
92
+ // installed. A file added under hooks/lib/ appeared on users' disks with no
93
+ // manifest entry, so "is the manifest complete" was unanswerable by reading
94
+ // the manifest — the exact question REQ-DEPLOY-002 exists to make answerable.
95
+ // Copying the declared list makes the manifest the actual install plan.
96
+ const { MODULE_FILES } = require('./deploy-manifest.js');
97
+ MODULE_FILES.forEach(rel => {
98
+ const src = path.join(srcDir, 'hooks', rel);
99
+ if (!fs.existsSync(src)) return;
100
+ const dest = path.join(destDir, rel);
101
+ fs.mkdirSync(path.dirname(dest), { recursive: true });
102
+ fs.copyFileSync(src, dest);
103
+ // Only executables need the bit; a .ps1/.cjs/.py helper does not, but setting
104
+ // it is harmless and keeps shell modules runnable the way they were before.
105
+ fs.chmodSync(dest, 0o755);
106
+ });
86
107
  }
87
108
 
88
109
  function copyAdapters(srcDir, destDir) {
89
110
  const adaptersDir = path.join(srcDir, 'adapters');
90
- const adapterCommon = path.join(srcDir, 'adapter-common.sh');
111
+ const { ADAPTER_COMMON } = require('./deploy-manifest.js');
112
+ const adapterCommon = path.join(srcDir, ADAPTER_COMMON);
91
113
  if (fs.existsSync(adapterCommon)) {
92
- fs.copyFileSync(adapterCommon, path.join(destDir, 'adapter-common.sh'));
114
+ fs.copyFileSync(adapterCommon, path.join(destDir, ADAPTER_COMMON));
93
115
  }
94
116
  // Shared shell helpers the fragments `source` at runtime (ccn-ratchet.sh and
95
117
  // friends). Without this, gate-3.sh resolves $GATE_DIR/lib/ccn-ratchet.sh to a
package/lib/uninstall.js CHANGED
@@ -10,6 +10,7 @@ const {
10
10
  GLOBAL_ADAPTERS_DIR,
11
11
  GLOBAL_MODULES_DIR,
12
12
  } = require('./shared-paths.js');
13
+ const { HOOK_FILES } = require('./deploy-manifest.js');
13
14
 
14
15
  const BACKUP_DIR = path.join(CONFIG_DIR, '.uninstall-backup');
15
16
 
@@ -865,14 +866,16 @@ function planHooksDirRemoval(hooksDir) {
865
866
  /**
866
867
  * Hook entry points xp-gate installs.
867
868
  *
868
- * This must stay in sync with `copyHooks()`'s `hookFiles` list, which is what
869
- * actually puts them on disk. `post-commit` was missing here (#714), so the
870
- * uninstaller classified its own hook as a third party's and kept it -- the
871
- * file contains nine `xp-gate` references and is installed unconditionally by
872
- * setup-global. The set is derived from the installer's list rather than
873
- * retyped, so the two cannot drift apart again.
869
+ * This must stay in sync with the list of hooks actually installed, which is
870
+ * what `copyHooks()` puts on disk. `post-commit` was missing here once (#714),
871
+ * so the uninstaller classified its own hook as a third party's and kept it —
872
+ * the file contains nine `xp-gate` references and is installed unconditionally
873
+ * by setup-global. The set is now read from the deploy manifest (REQ-DEPLOY-001,
874
+ * AC-DEPLOY-05) rather than retyped, so installer and uninstaller cannot drift
875
+ * apart again — and hook-module-resolution.sh is claimed too, which the old
876
+ * retyped list missed.
874
877
  */
875
- const OWNED_HOOK_NAMES = ['pre-commit', 'pre-push', 'post-merge', 'post-commit'];
878
+ const OWNED_HOOK_NAMES = HOOK_FILES;
876
879
 
877
880
  /** 'git-lfs' when the file proves it, else null. Content-based: see doctor.js. */
878
881
  function foreignHookSource(filePath) {