@boyingliu01/xp-gate 0.37.2 → 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 (118) 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/common-process.ts +36 -7
  16. package/gates/gate-9.ts +17 -8
  17. package/gates/python-health.ts +215 -24
  18. package/hooks/adapter-common.sh +12 -2
  19. package/hooks/deploy-manifest.sh +100 -0
  20. package/hooks/gate-10.sh +99 -26
  21. package/hooks/gate-12-file-hygiene.sh +13 -1
  22. package/hooks/gate-driver.sh +120 -0
  23. package/hooks/gate-entries/gate-0-entry.sh +825 -0
  24. package/hooks/gate-entries/gate-1-entry.sh +767 -0
  25. package/hooks/gate-entries/gate-10-entry.sh +52 -0
  26. package/hooks/gate-entries/gate-11-entry.sh +120 -0
  27. package/hooks/gate-entries/gate-12-entry.sh +44 -0
  28. package/hooks/gate-entries/gate-12b-entry.sh +178 -0
  29. package/hooks/gate-entries/gate-12c-entry.sh +80 -0
  30. package/hooks/gate-entries/gate-13-entry.sh +584 -0
  31. package/hooks/gate-entries/gate-2-entry.sh +199 -0
  32. package/hooks/gate-entries/gate-3-entry.sh +53 -0
  33. package/hooks/gate-entries/gate-4-entry.sh +46 -0
  34. package/hooks/gate-entries/gate-5-entry.sh +1729 -0
  35. package/hooks/gate-entries/gate-6-entry.sh +658 -0
  36. package/hooks/gate-entries/gate-7-entry.sh +41 -0
  37. package/hooks/gate-entries/gate-8-entry.sh +33 -0
  38. package/hooks/gate-entries/gate-9-entry.sh +307 -0
  39. package/hooks/gate-entries/subdir-restore.sh +27 -0
  40. package/hooks/gate-registry.sh +51 -15
  41. package/hooks/hook-module-resolution.sh +73 -0
  42. package/hooks/install.sh +135 -0
  43. package/hooks/lib/now-ms.sh +55 -19
  44. package/hooks/lib/toolchain-path.sh +50 -6
  45. package/hooks/pre-commit +256 -5091
  46. package/hooks/pre-push +212 -25
  47. package/lib/__tests__/arch-config-template.test.js +190 -0
  48. package/lib/__tests__/baseline-shell-scope.test.js +60 -0
  49. package/lib/__tests__/crap-cli.test.js +14 -3
  50. package/lib/__tests__/deploy-manifest-check-wired.test.js +138 -0
  51. package/lib/__tests__/deploy-manifest-completeness.test.js +151 -0
  52. package/lib/__tests__/deploy-manifest-consumers-adapter-uninstall.test.js +40 -0
  53. package/lib/__tests__/deploy-manifest-consumers-no-private-lists.test.js +74 -0
  54. package/lib/__tests__/deploy-manifest-projection.test.js +66 -0
  55. package/lib/__tests__/deploy-manifest-shell-parity.test.js +108 -0
  56. package/lib/__tests__/deploy-manifest.test.js +97 -0
  57. package/lib/__tests__/doctor.test.js +51 -7
  58. package/lib/__tests__/gate-coverage.test.js +79 -12
  59. package/lib/__tests__/gate-numbering.test.js +28 -1
  60. package/lib/__tests__/install-sh-deploy-manifest.test.js +80 -0
  61. package/lib/__tests__/mirror-sync.test.js +45 -3
  62. package/lib/__tests__/npm-package.test.js +10 -7
  63. package/lib/__tests__/sastd-client.test.js +452 -0
  64. package/lib/__tests__/shared-utils-copyHooks-manifest.test.js +69 -0
  65. package/lib/__tests__/sprint-status-rework.test.js +1 -0
  66. package/lib/arch-config-template.js +87 -0
  67. package/lib/baseline.js +54 -2
  68. package/lib/deploy-manifest.js +174 -0
  69. package/lib/doctor.js +46 -14
  70. package/lib/gate-capability.js +291 -0
  71. package/lib/gate-coverage.js +194 -74
  72. package/lib/gate-identity.js +349 -0
  73. package/lib/gate-runner.js +11 -1
  74. package/lib/hook-module-resolution.js +27 -0
  75. package/lib/init.js +72 -5
  76. package/lib/mattpocock-license-verdict.json +1 -1
  77. package/lib/sastd-client.js +534 -0
  78. package/lib/shared-utils.js +31 -9
  79. package/lib/uninstall.js +10 -7
  80. package/lib/update-hooks.js +27 -18
  81. package/mock-policy/AGENTS.md +1 -1
  82. package/mutation/AGENTS.md +1 -1
  83. package/package.json +3 -1
  84. package/plugins/claude-code/.claude-plugin/plugin.json +1 -1
  85. package/plugins/claude-code/skills/delphi-review/AGENTS.md +1 -1
  86. package/plugins/claude-code/skills/sprint-flow/AGENTS.md +1 -1
  87. package/plugins/claude-code/skills/test-specification-alignment/AGENTS.md +2 -2
  88. package/plugins/dsh/package.json +1 -1
  89. package/plugins/dsh/skills/delphi-review/AGENTS.md +1 -1
  90. package/plugins/dsh/skills/sprint-flow/AGENTS.md +1 -1
  91. package/plugins/dsh/skills/test-specification-alignment/AGENTS.md +2 -2
  92. package/plugins/opencode/package.json +1 -1
  93. package/plugins/opencode/skills/delphi-review/AGENTS.md +1 -1
  94. package/plugins/opencode/skills/sprint-flow/AGENTS.md +1 -1
  95. package/plugins/opencode/skills/test-specification-alignment/AGENTS.md +2 -2
  96. package/plugins/qoder/plugin.json +1 -1
  97. package/plugins/qoder/skills/delphi-review/AGENTS.md +1 -1
  98. package/plugins/qoder/skills/sprint-flow/AGENTS.md +1 -1
  99. package/plugins/qoder/skills/test-specification-alignment/AGENTS.md +2 -2
  100. package/principles/AGENTS.md +1 -1
  101. package/principles/__tests__/analyzer.test.ts +2 -1
  102. package/principles/__tests__/config-enforcement.test.ts +1 -0
  103. package/principles/__tests__/types.test.ts +1 -0
  104. package/principles/adapters/base.ts +14 -1
  105. package/principles/adapters/duplication.ts +134 -0
  106. package/principles/rules/__tests__/clean-code/large-file.test.ts +2 -1
  107. package/principles/rules/clean-code/code-duplication.ts +75 -9
  108. package/principles/types.ts +39 -0
  109. package/scripts/__tests__/check-mattpocock-license.test.js +36 -3
  110. package/scripts/__tests__/sync-package-content.test.js +12 -2
  111. package/scripts/generate-mirrors.cjs +125 -0
  112. package/scripts/sync-package-content.js +64 -20
  113. package/skills/delphi-review/AGENTS.md +1 -1
  114. package/skills/sprint-flow/AGENTS.md +1 -1
  115. package/skills/test-specification-alignment/AGENTS.md +2 -2
  116. package/adapters/gate-9.sh +0 -245
  117. package/gate-9.sh +0 -245
  118. package/hooks/gate-9.sh +0 -245
@@ -124,8 +124,18 @@ function seedCanonicalSources(realRoot, destRoot) {
124
124
  const srcRoot = path.join(real, 'src');
125
125
  seedSrcModules(srcRoot, dest);
126
126
  fs.mkdirSync(path.join(dest, 'src', 'npm-package', 'scripts'), { recursive: true });
127
- for (const rel of ['scripts/sync-package-content.js', 'package.json']) {
128
- fs.copyFileSync(path.join(srcRoot, 'npm-package', rel), path.join(dest, 'src', 'npm-package', rel));
127
+ // `lib/deploy-manifest.js` is required unconditionally by syncHooks (REQ-DEPLOY-001):
128
+ // the hook list is read from the manifest rather than retyped. `seedSrcModules`
129
+ // deliberately skips the whole `src/npm-package/` tree, so without this entry the
130
+ // seeded worktree has no manifest and every syncHooks case fails with
131
+ // "Cannot find module .../lib/deploy-manifest.js" -- 11 false failures that read
132
+ // as a sync defect. Copy the one file the script actually requires, not the tree.
133
+ const seededLibFiles = [path.join('lib', 'deploy-manifest.js')];
134
+ for (const rel of ['scripts/sync-package-content.js', 'package.json', ...seededLibFiles]) {
135
+ const from = path.join(srcRoot, 'npm-package', rel);
136
+ if (!fs.existsSync(from)) continue;
137
+ fs.mkdirSync(path.dirname(path.join(dest, 'src', 'npm-package', rel)), { recursive: true });
138
+ fs.copyFileSync(from, path.join(dest, 'src', 'npm-package', rel));
129
139
  }
130
140
  } catch (err) {
131
141
  // A half-seeded worktree makes the sync mirror a partial tree, which then
@@ -0,0 +1,125 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * @module generate-mirrors
4
+ * @test REQ-E1
5
+ * @intent Generate the npm package's mirror trees from their canonical sources.
6
+ *
7
+ * WHY THIS EXISTS. `src/npm-package/` must be self-contained: npm's `files`
8
+ * field cannot point at `../../githooks/`, so the published tarball
9
+ * unavoidably carries copies. What is optional is whether those copies are
10
+ * also in git. Keeping them there meant 416 files / 48167 lines of
11
+ * byte-identical duplication, and every one of them a place to edit by
12
+ * mistake: #683 shipped a 4953-byte-stale gate-3.sh, v0.27.3 shipped a
13
+ * mirror-only fix that the next publish rolled back, and #717 sent a C#
14
+ * SAST fix into a file no hook sourced.
15
+ *
16
+ * P1-E step 1 moves the largest tree (`adapters/`, 199 files) out of
17
+ * version control. Once it is generated, "edit the wrong copy" stops being
18
+ * detectable-but-possible and becomes physically impossible: there is no
19
+ * second copy to edit until a build creates one.
20
+ *
21
+ * THE CONTRACT, and it is the whole correctness argument: generating from a
22
+ * clean canonical tree must reproduce the previously committed mirror
23
+ * byte-for-byte. That is what mirror-parity now asserts, and it is a
24
+ * stronger claim than "the two committed trees are equal" -- the old check
25
+ * could only ever confirm that two copies happened to agree, while the new
26
+ * one tests the generator itself.
27
+ *
28
+ * WHY A WRAPPER AND NOT THE SYNC SCRIPT DIRECTLY. `prepare` runs on every
29
+ * `npm install`, including on machines where `plugins/dsh/lib/` has not been
30
+ * built, and `sync-package-content.js` aborts in that case with
31
+ * "[sync] ERROR: plugins/dsh/lib/index.js is missing". An install must not
32
+ * fail because a gitignored build artefact is absent -- but a missing
33
+ * adapter tree is worse than a failed install, because the package would
34
+ * then be built with the tree missing entirely.
35
+ *
36
+ * So: generate the mirrors that cannot fail (adapters first, the one this
37
+ * step owns), and treat the rest as best-effort with a visible warning. A
38
+ * silent skip here would recreate the exact failure this module exists to
39
+ * remove -- a package that ships without the files it promises.
40
+ */
41
+ 'use strict';
42
+
43
+ const fs = require('node:fs');
44
+ const path = require('node:path');
45
+
46
+ const PKG_ROOT = path.resolve(__dirname, '..');
47
+ const REPO_ROOT = path.resolve(PKG_ROOT, '..', '..');
48
+
49
+ /** Mirrors generated here, each with the canonical tree it comes from. */
50
+ const GENERATED_TREES = Object.freeze([
51
+ { mirror: 'adapters', canonical: path.join(REPO_ROOT, 'githooks', 'adapters') },
52
+ ]);
53
+
54
+ function quiet(argv) {
55
+ return argv.includes('--quiet');
56
+ }
57
+
58
+ function countFiles(dir) {
59
+ if (!fs.existsSync(dir)) return 0;
60
+ let total = 0;
61
+ const walk = (current) => {
62
+ for (const entry of fs.readdirSync(current, { withFileTypes: true })) {
63
+ const full = path.join(current, entry.name);
64
+ if (entry.isDirectory()) walk(full);
65
+ else if (entry.isFile()) total += 1;
66
+ }
67
+ };
68
+ walk(dir);
69
+ return total;
70
+ }
71
+
72
+ function main(argv = process.argv.slice(2)) {
73
+ const silent = quiet(argv);
74
+ const say = (message) => {
75
+ if (!silent) process.stderr.write(`${message}\n`);
76
+ };
77
+
78
+ // 1. The tree this step owns. Absence of the canonical source is a defect in the
79
+ // checkout, not a normal state, so it fails rather than skipping.
80
+ const [{ mirror, canonical }] = GENERATED_TREES;
81
+ if (!fs.existsSync(canonical)) {
82
+ process.stderr.write(
83
+ `[generate-mirrors] CANNOT GENERATE: canonical tree missing: ${canonical}\n`
84
+ + ' The package would build without its adapters. Refusing to continue '
85
+ + 'silently -- a package missing the files it ships is the failure this\n'
86
+ + ' generator exists to prevent.\n',
87
+ );
88
+ return 1;
89
+ }
90
+
91
+ let sync;
92
+ try {
93
+ // Required lazily: sync-package-content.js runs its own main at require-time
94
+ // when invoked directly, and the eager import would make every caller pay for
95
+ // the skills/plugin discovery even when only the adapters mirror is wanted.
96
+ // No eslint-disable needed: this file is CommonJS and `global-require` does
97
+ // not fire here (the directive that used to sit on this line was itself the
98
+ // reported problem -- an unused disable is a warning, and Gate 1 allows zero).
99
+ ({ syncAdapters: sync } = require('./sync-package-content.js'));
100
+ } catch (error) {
101
+ process.stderr.write(`[generate-mirrors] cannot load sync-package-content.js: ${error.message}\n`);
102
+ return 1;
103
+ }
104
+
105
+ if (typeof sync !== 'function') {
106
+ process.stderr.write('[generate-mirrors] sync-package-content.js does not export syncAdapters\n');
107
+ return 1;
108
+ }
109
+
110
+ const entries = sync();
111
+ const files = countFiles(path.join(PKG_ROOT, mirror));
112
+ if (files === 0) {
113
+ process.stderr.write(`[generate-mirrors] ERROR: ${mirror}/ generated 0 files from ${canonical}\n`);
114
+ return 1;
115
+ }
116
+ say(`[generate-mirrors] ${mirror}/ (${entries} entries, ${files} files)`);
117
+
118
+ return 0;
119
+ }
120
+
121
+ if (require.main === module) {
122
+ process.exit(main());
123
+ }
124
+
125
+ module.exports = { main, GENERATED_TREES, countFiles };
@@ -210,33 +210,53 @@ function syncAdapters() {
210
210
  // because `resolveGateScript()` falls back to `<adapterDir>/gate-<n>.sh` in a
211
211
  // TS-less install, and #532 requires the gate-9 verdict block to stay
212
212
  // byte-identical across those copies. Four of them had silently lagged the
213
- // canonical gates (gate-3.sh by 4953 bytes, missing the #632 fix). Nothing
214
- // failed only because the package-root copy is written later and wins.
213
+ // canonical gates (gate-3.sh by 4953 bytes, missing the #632 fix).
215
214
  //
216
- // Re-mirror them here so the invariant is maintained, not merely observed.
217
- // The names are taken FROM the adapters directory: this only refreshes copies
218
- // that already exist, it never adds a gate script to `adapters/` that was not
219
- // deliberately placed there.
215
+ // P1-E step 1 changed WHERE this can be repaired. The old code wrote the
216
+ // canonical copies (`githooks/adapters/<f>`) to fix them — which is a build step
217
+ // MUTATING the source of truth. That was survivable while the mirror was tracked
218
+ // and hand-maintained, because a human reviewed the diff. Now that the mirror is
219
+ // generated and gitignored, the same write CREATES files in the canonical tree:
220
+ // running the generator once produced an untracked `githooks/adapters/sprint-gate.sh`
221
+ // that nothing had ever committed, and the freshly generated mirror then held a
222
+ // file its source did not.
223
+ //
224
+ // So the canonical tree is read-only here. A canonical adapter gate copy that
225
+ // disagrees with `githooks/<f>` is REPORTED rather than silently rewritten: the
226
+ // fix belongs in a commit that a reviewer can see, not in a side effect of a
227
+ // publish step. The generated mirror always takes the canonical adapter copy
228
+ // verbatim (syncAdapters copies the tree), so drift shows up as a mirror-vs-source
229
+ // mismatch in `check-hook-mirror.sh` instead of being papered over.
220
230
  const adaptersRoot = path.join(githooksDir, 'adapters');
221
- let refreshed = 0;
222
231
  let adaptersNames = [];
223
232
  try {
224
233
  adaptersNames = fs.readdirSync(adaptersRoot);
225
234
  } catch {
226
235
  adaptersNames = [];
227
236
  }
237
+ const staleAdapterGates = [];
228
238
  for (const f of adaptersNames) {
229
239
  const isGateScript = f.endsWith('.sh') && (f.startsWith('gate-') || f === 'sprint-gate.sh');
230
240
  const canonical = path.join(githooksDir, f);
231
241
  if (!isGateScript || !fs.existsSync(canonical)) continue;
232
- const mirror = path.join(adaptersRoot, f);
233
- const a = fs.readFileSync(canonical);
234
- if (fs.existsSync(mirror) && fs.readFileSync(mirror).equals(a)) continue;
235
- fs.copyFileSync(canonical, mirror);
236
- console.error(`[sync] refreshed stale adapter gate mirror: ${f}`);
237
- refreshed += 1;
238
- }
239
- return copied + gateFiles.length + refreshed;
242
+ const adapterCopy = path.join(adaptersRoot, f);
243
+ try {
244
+ if (fs.readFileSync(adapterCopy).equals(fs.readFileSync(canonical))) continue;
245
+ } catch {
246
+ continue;
247
+ }
248
+ staleAdapterGates.push(f);
249
+ }
250
+ if (staleAdapterGates.length > 0) {
251
+ // Loud, not fatal: the generated mirror still carries the adapter copy verbatim,
252
+ // so the package is consistent; what is inconsistent is the canonical tree, and
253
+ // that needs a human to commit the refresh.
254
+ console.error(
255
+ `[sync] WARNING: canonical adapter gate copies differ from githooks/<name>: ${staleAdapterGates.join(', ')}`
256
+ + ' — refresh them in a commit; this script no longer writes the source tree.',
257
+ );
258
+ }
259
+ return copied + gateFiles.length;
240
260
  }
241
261
 
242
262
  function syncHooks() {
@@ -250,12 +270,19 @@ function syncHooks() {
250
270
  fs.copyFileSync(adapterCommonSrc, path.join(PKG_ROOT, 'adapter-common.sh'));
251
271
  }
252
272
 
253
- // #505: hook-module-resolution.sh is GENERATED, but it must still ship beside
254
- // pre-commit — the hook aborts with FATAL when it is missing, by design.
255
- const HOOK_FILES = ['pre-commit', 'pre-push', 'post-commit', 'post-merge', 'adapter-common.sh', 'hook-module-resolution.sh'];
273
+ // REQ-DEPLOY-001: the hook list is the deploy manifest's, not a local retyped
274
+ // array. Gate 12b requires a package mirror for every `githooks/*` file the
275
+ // diff touches, so this list and the manifest must not disagree — when they
276
+ // did, `sync --fix` (the command Gate 12b itself prints) could not produce
277
+ // the mirror and the commit was un-committable.
278
+ const manifest = require(path.join(__dirname, '..', 'lib', 'deploy-manifest.js'));
279
+ const HOOK_FILES = [...manifest.HOOK_FILES, manifest.ADAPTER_COMMON];
280
+ // Installers are repo-side tooling rather than published hooks, but Gate 12b
281
+ // treats every githooks/* file alike, so they get a mirror too.
282
+ const INSTALLER_FILES = ['install.sh'];
256
283
  let copied = 0;
257
284
 
258
- for (const name of HOOK_FILES) {
285
+ for (const name of [...HOOK_FILES, ...INSTALLER_FILES]) {
259
286
  const srcPath = path.join(SRC, name);
260
287
  const dstPath = path.join(DST, name);
261
288
  if (fs.existsSync(srcPath)) {
@@ -285,6 +312,16 @@ function syncHooks() {
285
312
  copied += gateFiles.length;
286
313
  }
287
314
 
315
+ // #505 先例(hook-module-resolution.sh):生成的 shell 投影 deploy-manifest.sh
316
+ // 本身也必须镜像到包内(install.sh source 它,Gate 12b parity 强制)。投影
317
+ // 非 hook/gate 清单成员,故显式同步;漏同步由 Gate 12b 镜像 parity 拦截
318
+ // (本会话实证:投影首次落地时 Gate 12b BLOCK 了提交)。
319
+ const projectionSrc = path.join(SRC, 'deploy-manifest.sh');
320
+ if (fs.existsSync(projectionSrc)) {
321
+ fs.copyFileSync(projectionSrc, path.join(DST, 'deploy-manifest.sh'));
322
+ copied += 1;
323
+ }
324
+
288
325
  console.error(`[sync] hooks/ (${copied} entries)`);
289
326
  return copied;
290
327
  }
@@ -565,5 +602,12 @@ if (require.main === module) {
565
602
  // Requiring this script must not mutate the work tree: a test that only wants
566
603
  // checkDocsDrift/checkAdapterDrift used to trigger a full mirror sync at
567
604
  // require-time, which vitest-worktree-guard rightly reported as pollution.
568
- module.exports = { checkDocsDrift, checkAdapterDrift, checkPrePushDrift, checkPreCommitDrift };
605
+ module.exports = {
606
+ checkDocsDrift,
607
+ checkAdapterDrift,
608
+ checkPrePushDrift,
609
+ checkPreCommitDrift,
610
+ syncHooks,
611
+ syncAdapters,
612
+ };
569
613
  }
@@ -3,7 +3,7 @@
3
3
  **Generated:** 2026-11-04
4
4
  **Commit:** eb2097b0
5
5
  **Branch:** sprint/2026-11-03-02
6
- **Version:** 0.37.2.0
6
+ **Version:** 0.38.0.0
7
7
 
8
8
  ## OVERVIEW
9
9
  Delphi Consensus Review — multi-round anonymous expert review (≥90% threshold, exactly 3 experts with distinct executable model IDs). Supports design, requirements, and code-walkthrough modes.
@@ -3,7 +3,7 @@
3
3
  **Generated:** 2026-11-04
4
4
  **Commit:** eb2097b0
5
5
  **Branch:** sprint/2026-11-03-02
6
- **Version:** 0.37.2.0
6
+ **Version:** 0.38.0.0
7
7
 
8
8
  ## OVERVIEW
9
9
  **6-phase** development pipeline (v2.0 compact redesign, Issue #290): PREP → DESIGN → BUILD → VERIFY → SHIP → CLOSE. Phase 3/6 BUILD default build mode is **ralph-loop** (REQ-level iteration, 40-67% token savings vs parallel). HARD-GATE between DESIGN (2/6) and BUILD (3/6): design must pass Delphi review (≥90% consensus) before any coding.
@@ -3,7 +3,7 @@
3
3
  **Generated:** 2026-11-04
4
4
  **Commit:** eb2097b0
5
5
  **Branch:** sprint/2026-11-03-02
6
- **Version:** 0.37.2.0
6
+ **Version:** 0.38.0.0
7
7
 
8
8
  ## OVERVIEW
9
9
  Test-Specification Alignment Engine — two-stage validation ensuring tests accurately reflect requirements and design specs.
@@ -53,4 +53,4 @@ skills/test-specification-alignment/
53
53
  - Runs during BUILD (Phase 2) after TDD
54
54
  - Mandatory before gstack-ship release
55
55
  - Integrates with test-driven-development skill
56
- - Uses freeze skill to lock test directories during Phase 2
56
+ - Uses freeze skill to lock test directories during Phase 2
@@ -1,245 +0,0 @@
1
- #!/usr/bin/env bash
2
- # ============================================================================
3
- # ⚠️ DEAD CODE — NOT EXECUTED. Read this before changing anything here.
4
- # ============================================================================
5
- # This file is NOT sourced by githooks/pre-commit or githooks/pre-push (both
6
- # source count = 0; verify with: grep -c "gate-9.sh" githooks/pre-commit).
7
- # It is shipped by githooks/install.sh but never runs.
8
- #
9
- # The gate that actually runs semgrep SAST is githooks/gate-10.sh, and it
10
- # reports as `gate10_sast`. Gate 9 in the report is `gate9_build_integrity`
11
- # (Build Integrity), a different gate entirely.
12
- #
13
- # This mislabelling is not cosmetic: in #717 a C# SAST fix was first written
14
- # into THIS file, where it changed nothing, while .cs stayed ungoverned. The
15
- # C# ruleset loading that works lives in gate-10.sh. Do not relocate it here.
16
- #
17
- # Kept rather than deleted because githooks/install.sh:GATE_SCRIPTS ships it;
18
- # removing it is a separate change. See issue #717 walkthrough MC-03.
19
- # ============================================================================
20
- # ============================================================================
21
- # GATE 9: Semgrep SAST Security Scan
22
- # Detects security vulnerabilities (SQL injection, XSS, etc.) in staged files
23
- # Tool: semgrep -- https://semgrep.dev
24
- # ============================================================================
25
- # #532: this is a legacy gate-9 fallback copy, kept alive by
26
- # resolveGateScript(9) in TS-less deployments (xp-gate gate sast without the
27
- # src/gates/gate-9.ts entry). The verdict semantics below are ported from
28
- # gate-10.sh (the #518 fix, v0.21.0) — the verdict block must stay byte
29
- # identical across githooks/gate-9.sh, githooks/gates/gate-9-sast-security.sh
30
- # and githooks/adapters/gate-9.sh; parity is asserted by
31
- # githooks/__tests__/issue-532-gate9-verdict.test.bats (AC-A-02-04).
32
-
33
- 2>&1 echo ""
34
- 2>&1 echo "→ Gate 9: Semgrep SAST Security Scan..."
35
- GATE_9_START=$(gate_start_ms)
36
-
37
- GATE_9_STATUS=""
38
-
39
- # Semgrep availability check
40
- SEMGREP_CMD=""
41
- if command -v semgrep >/dev/null 2>&1; then
42
- SEMGREP_CMD="semgrep"
43
- elif [ -f "$HOME/.local/bin/semgrep" ]; then
44
- SEMGREP_CMD="$HOME/.local/bin/semgrep"
45
- fi
46
-
47
- if [ -z "$SEMGREP_CMD" ]; then
48
- echo " ⚠️ WARN - semgrep not installed — SAST scanning unavailable"
49
- echo " Install: brew install semgrep (macOS) | pip install semgrep (Linux) | pip install semgrep (Windows)"
50
- echo " Pre-cache rules: semgrep --config=p/security-audit"
51
- echo " Gate 9: SAST Security (WARN, semgrep not installed)"
52
- GATE_9_STATUS="WARN"
53
- else
54
- # Get staged files filtered to Semgrep-supported languages.
55
- #
56
- # #616: under `--all` the index is usually empty, so the staged diff yielded no
57
- # files and the gate reported SKIPPED -- "no supported language files changed"
58
- # -- for a run whose whole purpose was to scan the tree. Same fail-open shape
59
- # #589 fixed in Gate 3, one layer down: the CLI says the tree was checked and
60
- # the fragment checks a diff that does not exist. The runner exports GATE_SCOPE;
61
- # read it and enumerate tracked files instead.
62
- if [ "${GATE_SCOPE:-diff}" = "all" ]; then
63
- echo " Scope: --all (scanning tracked files, not the index)"
64
- SEMGREP_FILES=$(git ls-files 2>/dev/null | grep -E '\.(ts|tsx|js|jsx|py|go|java|c|cpp|cs|rb|php|scala|swift)$' || true)
65
- else
66
- SEMGREP_FILES=$(git diff --cached --name-only --diff-filter=ACM 2>/dev/null | grep -E '\.(ts|tsx|js|jsx|py|go|java|c|cpp|cs|rb|php|scala|swift)$' || true)
67
- fi
68
-
69
- if [ -z "$SEMGREP_FILES" ]; then
70
- echo " ⏭️ SKIPPED - SAST (no supported language files changed)"
71
- GATE_9_STATUS="SKIP"
72
- else
73
- # One path per line into an array. Quoting the newline-joined list would hand
74
- # semgrep ONE argument containing newlines -> "Invalid scanning root" once
75
- # >=2 files are staged (#490). Same defect class as the Gate 4 --files fix
76
- # (#457): an array is the only form that keeps spaces intact AND splits files.
77
- #
78
- # Each element gets a ./ prefix: a tracked path may legitimately start with
79
- # '-' (`git add -- ./-o.ts`), and bare in argv that element reads as an option
80
- # and rewrites the scan it was meant to constrain. ./ is a path to every
81
- # argument parser.
82
- #
83
- # The unquoted heredoc below expands $SEMGREP_FILES once, then feeds literal
84
- # lines to `read`; bash never rescans the result for separators. Its correct
85
- # reading rests on one property of the producer above, not of the loop:
86
- # `git diff --cached --name-only` terminates paths with LF and quotes control
87
- # characters (a CR in a name arrives as the four bytes \215, never as a bare
88
- # CR), so one line is exactly one path. Asserted for spaces and a leading '-'
89
- # by AC-490-04.
90
- SEMGREP_ARGS=()
91
- SEMGREP_FILE_COUNT=0
92
- SEMGREP_DIRS_SEEN=$'\n'
93
- while IFS= read -r _semgrep_file; do
94
- [ -n "$_semgrep_file" ] || continue
95
- SEMGREP_FILE_COUNT=$((SEMGREP_FILE_COUNT + 1))
96
- SEMGREP_ARGS+=("--include=${_semgrep_file##*/}")
97
- _semgrep_dir="./${_semgrep_file%/*}"
98
- # A repo-root file has no directory component ("./x.ts" strips to "./").
99
- [ "$_semgrep_dir" = "./" ] && _semgrep_dir="."
100
- case "$SEMGREP_DIRS_SEEN" in
101
- *"$_semgrep_dir"*) : ;;
102
- *) SEMGREP_ARGS+=("$_semgrep_dir"); SEMGREP_DIRS_SEEN="$SEMGREP_DIRS_SEEN$_semgrep_dir"$'\n' ;;
103
- esac
104
- done <<EOF
105
- $SEMGREP_FILES
106
- EOF
107
-
108
- # The verdict is parsed from the JSON with node (see below), so node is a
109
- # hard dependency of this gate — check it BEFORE spending a semgrep run
110
- # (#518 R2): without it we would silently SKIP every finding as
111
- # "unparseable" and lose the whole security net on minimal CI images.
112
- if ! command -v node >/dev/null 2>&1; then
113
- echo " ⚠️ WARN - node is not installed — Gate 9 needs it to parse semgrep's JSON verdict"
114
- echo " Install node (https://nodejs.org); without it SAST findings cannot be classified"
115
- echo " ⏭️ SKIPPED - SAST (node not installed)"
116
- GATE_9_STATUS="SKIP"
117
- else
118
-
119
- # Run semgrep with JSON output. stdout and stderr are captured SEPARATELY:
120
- # --json writes findings to stdout, progress/summary lines to stderr, and the
121
- # old `2>&1` merge poisoned the very JSON the verdict now depends on (#518).
122
- # SEMGREP_OUTPUT keeps its name and role — what the tool said, printed on the
123
- # SKIP path (AC-475-04).
124
- #
125
- # #518: the exit code does NOT carry the verdict. semgrep exits 0 even with
126
- # ERROR-severity findings, and its exit-code semantics have drifted across
127
- # versions and platforms (upstream currently reports findings WITH --error
128
- # as exit 1 and failures as 2, but that mapping is not something a gate
129
- # should bet on). The JSON carries what the exit code never could —
130
- # per-severity counts — so the verdict is read from the JSON and the exit
131
- # code is demoted to "did the tool itself run". --error stays OFF: it would
132
- # add nothing the JSON does not already provide, and keeping it off leaves
133
- # failure exit codes unambiguous for the #475 diagnostics path.
134
- # #717: p/security-audit carries NO C# rules. Measured: a .cs file with a
135
- # textbook SQL injection (string-concatenated SqlCommand) and a
136
- # Process.Start command injection produced 0 findings under
137
- # p/security-audit and 1 ERROR under p/csharp. Since gate-9.sh:45 lists
138
- # `cs` in the file filter, .cs was accepted and then scanned by a ruleset
139
- # that cannot see C# -- the identical "filter looks like coverage" defect
140
- # this issue removed from Gate 4. p/csharp is loaded IN ADDITION to
141
- # p/security-audit (not instead of: the security-audit rules still apply
142
- # to the other languages in a mixed commit).
143
- SEMGREP_RULES=(--config=p/security-audit)
144
- if printf "%s
145
- " "$SEMGREP_FILES" | grep -qE ".cs$"; then
146
- SEMGREP_RULES+=(--config=p/csharp)
147
- fi
148
- SEMGREP_STDOUT_FILE=$(mktemp)
149
- SEMGREP_OUTPUT=$("$SEMGREP_CMD" scan "${SEMGREP_RULES[@]}" --json --disable-version-check "${SEMGREP_ARGS[@]}" 2>&1 >"$SEMGREP_STDOUT_FILE")
150
- SEMGREP_EXIT=$?
151
-
152
- # One node pass over the JSON: first line = verdict counts, remaining lines =
153
- # finding details. The severity vocabulary is the UNION of the two scales
154
- # (#518): semgrep's own ERROR is its most severe tier (it maps to the old
155
- # CRITICAL/HIGH → BLOCK intent), its WARNING/INFO align with the old
156
- # MEDIUM/LOW → warnings-only tier. Anything OUTSIDE both lists (missing,
157
- # empty, or a future/new tier) counts as BLOCKING — a security gate must
158
- # fail closed on severities it does not recognize (#518 R2). Parsing
159
- # failure degrades to PARSE=FAIL — a fail-closed SKIP below, never a PASS.
160
- SEMGREP_VERDICT=$(node -e '
161
- let d="";process.stdin.on("data",c=>d+=c);process.stdin.on("end",()=>{
162
- let data;try{data=JSON.parse(d);}catch(e){console.log("PARSE=FAIL RESULTS=0 ERRORS=0 BLOCKING=0 WARNINGS=0");return;}
163
- const results=data.results||[];const errors=data.errors||[];
164
- const sev=r=>((r.extra&&r.extra.severity)||"").toUpperCase();
165
- const WARNV=["WARNING","INFO","MEDIUM","LOW"];
166
- let b=0,w=0;results.forEach(r=>{if(WARNV.indexOf(sev(r))>=0)w++;else b++;});
167
- console.log("PARSE=OK RESULTS="+results.length+" ERRORS="+errors.length+" BLOCKING="+b+" WARNINGS="+w);
168
- results.slice(0,5).forEach(r=>{const extra=r.extra||{};const s=sev(r)||"UNKNOWN";
169
- console.log(" ["+s+"] "+(r.check_id||"unknown"));
170
- console.log(" "+(r.path||"unknown")+":"+((r.start&&r.start.line)||"?")+" → "+(extra.message||"").slice(0,80));
171
- console.log("");});
172
- });' < "$SEMGREP_STDOUT_FILE") || SEMGREP_VERDICT="PARSE=FAIL RESULTS=0 ERRORS=0 BLOCKING=0 WARNINGS=0"
173
-
174
- PARSE_LINE=$(printf '%s\n' "$SEMGREP_VERDICT" | sed -n '1p')
175
- FINDING_DETAILS=$(printf '%s\n' "$SEMGREP_VERDICT" | sed -n '2,$p')
176
- V_PARSE=$(printf '%s\n' "$PARSE_LINE" | sed -n 's/^PARSE=\([A-Z]*\) .*/\1/p')
177
- V_RESULTS=$(printf '%s\n' "$PARSE_LINE" | sed -n 's/.* RESULTS=\([0-9]*\) .*/\1/p')
178
- V_ERRORS=$(printf '%s\n' "$PARSE_LINE" | sed -n 's/.* ERRORS=\([0-9]*\) .*/\1/p')
179
- V_BLOCKING=$(printf '%s\n' "$PARSE_LINE" | sed -n 's/.* BLOCKING=\([0-9]*\) .*/\1/p')
180
- V_WARNINGS=$(printf '%s\n' "$PARSE_LINE" | sed -n 's/.* WARNINGS=\([0-9]*\)$/\1/p')
181
- # Keep the raw stdout tail for the unparseable branch's diagnostics BEFORE
182
- # the temp file goes away (#518 R2: stderr alone often says nothing there).
183
- SEMGREP_STDOUT_TAIL=$(tail -5 "$SEMGREP_STDOUT_FILE" 2>/dev/null)
184
- rm -f "$SEMGREP_STDOUT_FILE"
185
-
186
- # Fail closed: an unparseable payload OR an OK parse with any missing count
187
- # field (verdict-line format drift) must SKIP, never silently degrade to
188
- # PASS (#518).
189
- if [ "$V_PARSE" != "OK" ] || [ -z "$V_RESULTS" ] || [ -z "$V_ERRORS" ] || [ -z "$V_BLOCKING" ] || [ -z "$V_WARNINGS" ]; then
190
- # Unparseable output: nothing the exit code claims can be trusted (#518).
191
- # Fail closed — SKIP with diagnostics, never a PASS.
192
- echo " ⚠️ semgrep output unparseable or verdict fields missing (exit code ${SEMGREP_EXIT}) — cannot determine verdict"
193
- if [ -n "$SEMGREP_OUTPUT" ]; then
194
- echo " ── what semgrep reported on stderr ──"
195
- printf '%s\n' "$SEMGREP_OUTPUT" | tail -10 | sed 's/^/ /'
196
- fi
197
- if [ -n "$SEMGREP_STDOUT_TAIL" ]; then
198
- echo " ── what semgrep wrote to stdout (tail) ──"
199
- printf '%s\n' "$SEMGREP_STDOUT_TAIL" | sed 's/^/ /'
200
- fi
201
- echo " ⏭️ SKIPPED - SAST (semgrep output unparseable)"
202
- GATE_9_STATUS="SKIP"
203
- elif [ "$V_RESULTS" -eq 0 ] && { [ "$V_ERRORS" -gt 0 ] || [ "$SEMGREP_EXIT" -ne 0 ]; }; then
204
- # Nothing was scanned to a verdict: semgrep either failed outright
205
- # (nonzero exit) or completed but reported scan errors for every input
206
- # (#518 R2: exit 0 + results:[] + errors:[{...}] used to fall through to
207
- # PASS). An operational failure must neither block nor claim a pass
208
- # (#475 kept).
209
- echo " ⚠️ semgrep exit=${SEMGREP_EXIT}, scan errors=${V_ERRORS}, findings=${V_RESULTS} — nothing to judge"
210
- if [ -n "$SEMGREP_OUTPUT" ]; then
211
- echo " ── what semgrep reported ──"
212
- printf '%s\n' "$SEMGREP_OUTPUT" | tail -10 | sed 's/^/ /'
213
- fi
214
- echo " ⏭️ SKIPPED - SAST (semgrep runtime error)"
215
- GATE_9_STATUS="SKIP"
216
- elif [ "$V_BLOCKING" -gt 0 ]; then
217
- echo ""
218
- echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
219
- echo " GATE 9: Semgrep Security Gate"
220
- echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
221
- echo " CRITICAL/HIGH/ERROR: ${V_BLOCKING} ❌ BLOCKED"
222
- echo " MEDIUM/LOW/WARNING/INFO: ${V_WARNINGS} ⚠️ warning"
223
- echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
224
- echo " ❌ BLOCKED — blocking-severity vulnerability found"
225
- echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
226
- echo "$FINDING_DETAILS"
227
- # #717: name BOTH rulesets. A C# finding comes from p/csharp, so
228
- # pointing the author at p/security-audit alone reproduces zero hits.
229
- echo " Run 'semgrep scan --config=p/security-audit --config=p/csharp' to review all findings."
230
- GATE_9_STATUS="FAIL"
231
- exit 1
232
- else
233
- echo ""
234
- echo " ✅ PASSED - No blocking vulnerabilities (files scanned: $SEMGREP_FILE_COUNT)"
235
- if [ "$V_WARNINGS" -gt 0 ]; then
236
- echo " ⚠️ ${V_WARNINGS} non-blocking findings (warnings only)"
237
- echo "$FINDING_DETAILS"
238
- fi
239
- GATE_9_STATUS="PASS"
240
- fi
241
-
242
- fi # node available
243
- fi
244
- fi
245
- record_gate_audit "gate-9" "sast-security" "$GATE_9_STATUS" "0" "$GATE_9_START"