@boyingliu01/xp-gate 0.36.1 → 0.37.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (123) hide show
  1. package/adapters/cpp.sh +78 -10
  2. package/adapters/csharp.sh +58 -3
  3. package/adapters/gate-3.sh +15 -5
  4. package/adapters/gate-8.sh +131 -9
  5. package/adapters/typescript.sh +32 -8
  6. package/build-integrity/__tests__/import-resolver.test.ts +257 -0
  7. package/build-integrity/__tests__/quote-masker.test.ts +177 -0
  8. package/build-integrity/gate-10.ts +127 -9
  9. package/build-integrity/quote-masker.ts +266 -0
  10. package/gate-10.sh +66 -0
  11. package/gate-12-file-hygiene.sh +15 -7
  12. package/gate-13-compiler-strictness.sh +81 -1
  13. package/gate-3.sh +15 -5
  14. package/gate-6-layers.sh +375 -0
  15. package/gate-8.sh +131 -9
  16. package/hooks/gate-10.sh +66 -0
  17. package/hooks/gate-12-file-hygiene.sh +15 -7
  18. package/hooks/gate-13-compiler-strictness.sh +81 -1
  19. package/hooks/gate-3.sh +15 -5
  20. package/hooks/gate-6-layers.sh +375 -0
  21. package/hooks/gate-8.sh +131 -9
  22. package/hooks/gate-registry.sh +2 -2
  23. package/hooks/hook-module-resolution.sh +1 -1
  24. package/hooks/lib/assertion-quality.sh +8 -2
  25. package/hooks/lib/ccn-ratchet.sh +10 -0
  26. package/hooks/lib/layer-baseline.cjs +88 -0
  27. package/hooks/lib/typecheck.sh +28 -5
  28. package/hooks/pre-commit +376 -53
  29. package/hooks/pre-push +46 -13
  30. package/lib/__tests__/agent-runtime-journal.test.js +1 -1
  31. package/lib/__tests__/arch.test.js +9 -0
  32. package/lib/__tests__/audit-cli-contract.test.ts +1 -1
  33. package/lib/__tests__/check-alignment-reasons.test.mjs +11 -1
  34. package/lib/__tests__/check-all-skip-accounting.test.js +1 -1
  35. package/lib/__tests__/detect-deps-gate-identity.test.js +135 -0
  36. package/lib/__tests__/detect-deps.test.js +2 -1
  37. package/lib/__tests__/doctor-469-hook-env.test.js +7 -1
  38. package/lib/__tests__/doctor-arch-tools.test.js +169 -0
  39. package/lib/__tests__/doctor-delphi.test.js +1 -1
  40. package/lib/__tests__/doctor-drift-round2.test.js +4 -1
  41. package/lib/__tests__/doctor-executed-surface.test.js +45 -24
  42. package/lib/__tests__/doctor-module-drift.test.js +13 -7
  43. package/lib/__tests__/doctor-module-resolution-parity.test.js +74 -2
  44. package/lib/__tests__/doctor-tui-skill-freshness.test.js +21 -6
  45. package/lib/__tests__/doctor.test.js +17 -0
  46. package/lib/__tests__/gate-runner-tsx-invocation.test.js +149 -0
  47. package/lib/__tests__/gate-runner.test.js +23 -7
  48. package/lib/__tests__/init-gitignore.test.js +204 -0
  49. package/lib/__tests__/init.test.js +24 -3
  50. package/lib/__tests__/language-tools-build-file-install.test.js +82 -0
  51. package/lib/__tests__/language-tools-detect.test.js +61 -0
  52. package/lib/__tests__/mirror-sync.test.js +2 -0
  53. package/lib/__tests__/phase-transition.test.js +19 -1
  54. package/lib/__tests__/sprint-status-rework.test.js +32 -12
  55. package/lib/__tests__/test-alignment-range-guard.test.ts +82 -0
  56. package/lib/__tests__/test-alignment.test.ts +13 -3
  57. package/lib/__tests__/update-skill.test.js +2 -2
  58. package/lib/detect-deps.js +7 -1
  59. package/lib/doctor.js +81 -17
  60. package/lib/gate-runner.js +101 -7
  61. package/lib/hook-module-resolution.js +18 -6
  62. package/lib/init.js +136 -1
  63. package/lib/language-tools.js +217 -1
  64. package/lib/layer-baseline.cjs +88 -0
  65. package/lib/mattpocock-license-verdict.json +1 -1
  66. package/lib/principles.js +21 -6
  67. package/lib/test-alignment.ts +452 -55
  68. package/mock-policy/AGENTS.md +1 -1
  69. package/mutation/AGENTS.md +1 -1
  70. package/package.json +2 -1
  71. package/plugins/claude-code/.claude-plugin/plugin.json +1 -1
  72. package/plugins/claude-code/skills/delphi-review/.delphi-config.json.example +34 -24
  73. package/plugins/claude-code/skills/delphi-review/AGENTS.md +1 -1
  74. package/plugins/claude-code/skills/delphi-review/INSTALL.md +29 -1
  75. package/plugins/claude-code/skills/sprint-flow/AGENTS.md +1 -1
  76. package/plugins/claude-code/skills/test-specification-alignment/AGENTS.md +1 -1
  77. package/plugins/dsh/package.json +1 -1
  78. package/plugins/dsh/skills/delphi-review/.delphi-config.json.example +34 -24
  79. package/plugins/dsh/skills/delphi-review/AGENTS.md +1 -1
  80. package/plugins/dsh/skills/delphi-review/INSTALL.md +29 -1
  81. package/plugins/dsh/skills/sprint-flow/AGENTS.md +1 -1
  82. package/plugins/dsh/skills/test-specification-alignment/AGENTS.md +1 -1
  83. package/plugins/dsh/src/client.test.ts +1 -1
  84. package/plugins/dsh/src/command.test.ts +1 -1
  85. package/plugins/dsh/src/contract.test.ts +1 -1
  86. package/plugins/dsh/src/credentials.test.ts +1 -1
  87. package/plugins/opencode/package.json +1 -1
  88. package/plugins/opencode/skills/delphi-review/.delphi-config.json.example +34 -24
  89. package/plugins/opencode/skills/delphi-review/AGENTS.md +1 -1
  90. package/plugins/opencode/skills/delphi-review/INSTALL.md +29 -1
  91. package/plugins/opencode/skills/sprint-flow/AGENTS.md +1 -1
  92. package/plugins/opencode/skills/test-specification-alignment/AGENTS.md +1 -1
  93. package/plugins/qoder/plugin.json +1 -1
  94. package/plugins/qoder/skills/delphi-review/.delphi-config.json.example +34 -24
  95. package/plugins/qoder/skills/delphi-review/AGENTS.md +1 -1
  96. package/plugins/qoder/skills/delphi-review/INSTALL.md +29 -1
  97. package/plugins/qoder/skills/sprint-flow/AGENTS.md +1 -1
  98. package/plugins/qoder/skills/test-specification-alignment/AGENTS.md +1 -1
  99. package/principles/AGENTS.md +1 -1
  100. package/principles/__tests__/config-arch-group.test.ts +106 -0
  101. package/principles/__tests__/config-enforcement.test.ts +1 -1
  102. package/principles/adapters/control-nesting.ts +572 -0
  103. package/principles/adapters/csharp.ts +73 -42
  104. package/principles/adapters/java.ts +9 -5
  105. package/principles/adapters/typescript.ts +138 -176
  106. package/principles/config.ts +37 -2
  107. package/principles/index.ts +57 -4
  108. package/principles/reporter.ts +99 -65
  109. package/principles/rules/arch/__tests__/dependency.test.ts +180 -0
  110. package/principles/rules/arch/__tests__/naming.test.ts +133 -0
  111. package/principles/rules/arch/__tests__/shared.test.ts +113 -0
  112. package/principles/rules/arch/dependency.ts +264 -0
  113. package/principles/rules/arch/naming.ts +188 -0
  114. package/principles/rules/arch/shared.ts +169 -0
  115. package/principles/rules/exports.ts +26 -0
  116. package/principles/rules/index.ts +11 -18
  117. package/scripts/__tests__/sync-package-content.test.js +23 -1
  118. package/scripts/sync-package-content.js +8 -2
  119. package/skills/delphi-review/.delphi-config.json.example +34 -24
  120. package/skills/delphi-review/AGENTS.md +1 -1
  121. package/skills/delphi-review/INSTALL.md +29 -1
  122. package/skills/sprint-flow/AGENTS.md +1 -1
  123. package/skills/test-specification-alignment/AGENTS.md +1 -1
@@ -0,0 +1,375 @@
1
+ #!/usr/bin/env bash
2
+ # ============================================================================
3
+ # GATE 6 (layers): Layer Boundary Enforcement
4
+ #
5
+ # ── WHY THIS EXISTS ─────────────────────────────────────────────────────────
6
+ # `architecture.yaml` has declared layer boundaries since 2026-04, and Gate 6
7
+ # has never enforced them. #16 found the config schema didn't match archlint;
8
+ # the fix at the time was to stop passing `--config`, which made `layers:` dead
9
+ # config forever. #686 documented the resulting false green, and #728 measured
10
+ # that archlint 0.16.0's own `layer_violation` detector returns zero findings
11
+ # under every configuration (-A, -d, enabled: true, globs, exact paths).
12
+ #
13
+ # So the config was never wrong in the way the issue titles suggest. Nothing
14
+ # ever read it. This script reads it.
15
+ #
16
+ # Design: docs/plans/2026-11-07-gate-6-layer-enforcement-design.md
17
+ # Issues: #686 (dead config exposed), #691 (ARCH-04 layer direction rules),
18
+ # #728 (archlint detector is a no-op)
19
+ #
20
+ # ── WHY NOT ARCHLINT ────────────────────────────────────────────────────────
21
+ # #728 is not a configuration bug we can wait out: the detector is listed,
22
+ # enable-able, and produces no output. Depending on it means the gate's verdict
23
+ # is a statement about archlint, not about the code.
24
+ #
25
+ # A second reason is scope. The iteration-speed design (O4) shrinks archlint to
26
+ # a per-directory scope, but a layer violation is *by definition* an edge
27
+ # between two directories. An incremental scan structurally cannot see it. This
28
+ # checker always builds the whole-repo graph, and is cheap enough to afford it.
29
+ #
30
+ # ── VERDICT CONTRACT (inherited from pre-commit's java.sh / powershell.sh) ──
31
+ # 0 = PASS no layer violations
32
+ # 1 = FAIL new violations on this change (commit blocked)
33
+ # 2 = BLOCK config present but unusable (fail-closed)
34
+ # 3 = WARN no layer config declared, or violations only in baseline
35
+ #
36
+ # ── PERFORMANCE ─────────────────────────────────────────────────────────────
37
+ # One awk pass over the tree. No subprocess per file, no network, no cache to
38
+ # invalidate.
39
+ # ============================================================================
40
+
41
+ set -uo pipefail
42
+
43
+ LAYER_CONFIG="${XP_GATE_LAYER_CONFIG:-architecture.yaml}"
44
+ LAYER_BASELINE="${XP_GATE_LAYER_BASELINE:-.layer-baseline.json}"
45
+ LAYER_SCAN_ROOT="${XP_GATE_LAYER_SCAN_ROOT:-.}"
46
+ LAYER_REASON=""
47
+
48
+ # ─── Output helpers ─────────────────────────────────────────────────────────
49
+ _layers_say() { echo " $*"; }
50
+
51
+ _layers_verdict() {
52
+ local code="$1" text="$2" reason="${3:-}"
53
+ _layers_say "$text"
54
+ if [ -n "$reason" ]; then
55
+ _layers_say " reason: $reason"
56
+ LAYER_REASON="$reason"
57
+ fi
58
+ exit "$code"
59
+ }
60
+
61
+ # ─── 1. No config → WARN, never a silent pass ───────────────────────────────
62
+ # The whole defect class here began with "no config means nothing to check, and
63
+ # nothing to check means success".
64
+ if [ ! -f "$LAYER_CONFIG" ]; then
65
+ _layers_verdict 3 \
66
+ "⚠️ No layer config ($LAYER_CONFIG) — layer boundaries NOT checked." \
67
+ "no_layer_config"
68
+ fi
69
+
70
+ # ─── 2. Parse layers into a TSV: name, pattern, allowed, forbidden ──────────
71
+ LAYER_TSV=$(awk '
72
+ function trim(s) { gsub(/^[ \t]+|[ \t]+$/, "", s); return s }
73
+ function unq(s) { s = trim(s); gsub(/^["\047]|["\047]$/, "", s); return s }
74
+ # Split a YAML flow/block list into a comma-joined string of unquoted items.
75
+ function clean(v, k,i,p,out) {
76
+ v = trim(v); sub(/#.*$/, "", v); v = trim(v)
77
+ sub(/^\[/, "", v); sub(/\]$/, "", v)
78
+ k = split(v, p, ","); out = ""
79
+ for (i = 1; i <= k; i++) {
80
+ p[i] = unq(p[i])
81
+ if (p[i] != "") out = (out == "" ? p[i] : out "," p[i])
82
+ }
83
+ return out
84
+ }
85
+ # awk initialises every variable to "" rather than 0. `layerindent < 0` on an
86
+ # unset variable compares a string to a number and never fires, so the layer
87
+ # indent was never recorded and every layer was silently skipped — the same
88
+ # class of defect this gate exists to catch. Initialise explicitly.
89
+ # Emit one row per pattern so a layer can own several directories. Patterns
90
+ # are matched independently and longest-pattern-wins still resolves nesting.
91
+ # A layer with no pattern is emitted with an empty column: it can never match
92
+ # a file, and the scanner zero-classified guard reports that instead of
93
+ # treating it as clean.
94
+ function flush( k, i, p) {
95
+ if (name == "") return
96
+ k = split(pattern, p, ",")
97
+ if (k == 0) { print name "\t\t" allowed "\t" forbidden; name = ""; return }
98
+ for (i = 1; i <= k; i++) {
99
+ if (p[i] == "") continue
100
+ print name "\t" p[i] "\t" allowed "\t" forbidden
101
+ }
102
+ name = ""
103
+ }
104
+ BEGIN {
105
+ inlayers = 0; layerindent = -1
106
+ name = ""; pattern = ""; allowed = ""; forbidden = ""
107
+ }
108
+ /^[ \t]*#/ { next }
109
+ /^[ \t]*$/ { next }
110
+ {
111
+ line = $0
112
+ match(line, /^[ \t]*/); indent = RLENGTH
113
+ body = trim(line)
114
+ if (!inlayers) { if (body == "layers:") inlayers = 1; next }
115
+ # A key at indent 0 ends the layers block.
116
+ if (indent == 0) exit
117
+ if (layerindent < 0) layerindent = indent
118
+ # A \"<name>:\" line at the layer indent starts a new layer record.
119
+ # Supports both the map form (domain:) and an explicit name: field.
120
+ if (indent == layerindent && body ~ /^[A-Za-z0-9_-]+:[ \t]*$/) {
121
+ flush()
122
+ name = substr(body, 1, index(body, ":") - 1)
123
+ next
124
+ }
125
+ if (indent == layerindent && body ~ /^- /) { next }
126
+ if (name == "") next
127
+ if (body ~ /^name:/) { name = unq(substr(body, 6)) }
128
+ # `pattern:` and `patterns:` are both accepted. The singular form is the one
129
+ # the first tests happened to write; a layer that owns a directory plus a
130
+ # shared root needs more than one pattern, which is why `patterns:` occurs
131
+ # naturally. Accepting only one of the two made a correct config parse to an
132
+ # empty pattern list, which then matched no file and reported "0 violations"
133
+ # — the silent-pass shape this gate exists to remove.
134
+ else if (body ~ /^patterns?:/) { pattern = clean(substr(body, index(body, ":") + 1)) }
135
+ else if (body ~ /^allowedImports:/ || body ~ /^allowed_imports:/) { allowed = clean(substr(body, index(body, ":") + 1)) }
136
+ else if (body ~ /^forbiddenImports:/ || body ~ /^forbidden_imports:/) { forbidden = clean(substr(body, index(body, ":") + 1)) }
137
+ }
138
+ END { flush() }
139
+ ' "$LAYER_CONFIG" 2>/dev/null)
140
+
141
+ # ─── 3. Config present but unparseable → BLOCK (fail-closed) ───────────────
142
+ if [ -z "$LAYER_TSV" ]; then
143
+ _layers_verdict 2 \
144
+ "❌ BLOCKED - $LAYER_CONFIG exists but declares no usable layers." \
145
+ "layer_config_unparsable"
146
+ fi
147
+
148
+ LAYER_COUNT=$(printf '%s\n' "$LAYER_TSV" | grep -c . || true)
149
+
150
+ # ─── 4. Collect source files ────────────────────────────────────────────────
151
+ # Via git rather than find: `git ls-files` honours .gitignore by construction
152
+ # (no node_modules/dist/coverage exclusions to keep in sync with the ignore
153
+ # rules) and is faster on Windows — 0.5s vs 6.5s on this repo.
154
+ #
155
+ # Both tracked AND untracked-but-not-ignored files are included. A staged-only
156
+ # view would be wrong twice over: untracked files are exactly what an agent has
157
+ # just authored (the moment the check matters most), and `--cached` also misses
158
+ # a violation introduced in a file the commit does not touch. Layer membership
159
+ # is a property of the tree, not of the diff.
160
+ #
161
+ # Fallback to find for non-git fixtures (the BATS suite uses bare temp dirs).
162
+ if git rev-parse --is-inside-work-tree >/dev/null 2>&1; then
163
+ FILE_LIST=$(git ls-files --cached --others --exclude-standard -- \
164
+ '*.ts' '*.tsx' '*.js' '*.jsx' '*.mjs' '*.cjs' 2>/dev/null \
165
+ | grep -v '^\.layer-fixture' || true)
166
+ else
167
+ FILE_LIST=$(find "$LAYER_SCAN_ROOT" -type f \
168
+ \( -name '*.ts' -o -name '*.tsx' -o -name '*.js' -o -name '*.jsx' \
169
+ -o -name '*.mjs' -o -name '*.cjs' \) \
170
+ -not -path '*/node_modules/*' -not -path '*/.git/*' \
171
+ -not -path '*/dist/*' -not -path '*/coverage/*' \
172
+ -not -path '*/.stryker-tmp/*' -not -path '*/.layer-fixture*' 2>/dev/null | sed 's|^\./||')
173
+ fi
174
+
175
+ if [ -z "$FILE_LIST" ]; then
176
+ _layers_verdict 3 \
177
+ "⚠️ No source files under $LAYER_SCAN_ROOT — layer boundaries NOT checked." \
178
+ "no_source_files"
179
+ fi
180
+
181
+ # ─── 5. Scan imports and classify violations ────────────────────────────────
182
+ LAYER_TSV_FILE="${TMPDIR:-/tmp}/xp-layer-tsv.$$"
183
+ printf '%s\n' "$LAYER_TSV" > "$LAYER_TSV_FILE"
184
+
185
+ # Side channel for the scan's own bookkeeping (files seen / files classified).
186
+ # Defaults to 0/0 so a scan that dies before writing it reads as "classified
187
+ # nothing", which lands on the WARN path rather than a silent pass.
188
+ LAYER_STATS_FILE="${TMPDIR:-/tmp}/xp-layer-stats.$$"
189
+ : > "$LAYER_STATS_FILE"
190
+ LAYER_CLASSIFIED_FILES=0
191
+ LAYER_CLASSIFIED=0
192
+
193
+ # The file list goes in as ARGV, not on stdin: awk builds FILENAME from ARGV,
194
+ # and a stdin-driven loop leaves FILENAME empty — every file would be assigned
195
+ # layer 0 and the scan would report a clean tree. That is exactly the failure
196
+ # mode this gate exists to prevent, so the plumbing has to be right first.
197
+ FINDINGS=$(XP_LAYER_TSV="$LAYER_TSV_FILE" XP_LAYER_STATS="$LAYER_STATS_FILE" awk '
198
+ BEGIN {
199
+ n = 0
200
+ while ((getline row < ENVIRON["XP_LAYER_TSV"]) > 0) {
201
+ if (row == "") continue
202
+ split(row, f, "\t")
203
+ if (f[1] == "") continue
204
+ n++
205
+ lname[n] = f[1]; lpat[n] = f[2]; lallow[n] = f[3]
206
+ # Patterns are compiled once here. layer_of() runs twice per source file
207
+ # (once for the importer, once per resolved target); recompiling there
208
+ # meant ~5800 regex builds for this repo and dominated the 2s scan.
209
+ lre[n] = pat2re(f[2])
210
+ llen[n] = length(f[2])
211
+ }
212
+ close(ENVIRON["XP_LAYER_TSV"])
213
+ if (n == 0) { print "LAYER_TABLE_EMPTY" > "/dev/stderr"; exit 3 }
214
+ }
215
+ function pat2re(p, s) {
216
+ s = p
217
+ gsub(/[.]/, "\\.", s)
218
+ gsub(/[*][*]/, "\001", s)
219
+ gsub(/[*]/, "[^/]*", s)
220
+ gsub(/\001/, ".*", s)
221
+ return "^" s "$"
222
+ }
223
+ # Membership is decided by the LONGEST matching pattern, so a nested layer
224
+ # beats its parent regardless of declaration order. First-match-wins would
225
+ # make the verdict depend on YAML ordering.
226
+ function layer_of(path, best, blen, i) {
227
+ best = 0; blen = -1
228
+ for (i = 1; i <= n; i++) {
229
+ if (llen[i] > blen && path ~ lre[i]) { blen = llen[i]; best = i }
230
+ }
231
+ return best
232
+ }
233
+ function in_csv(list, val, k, j, p) {
234
+ k = split(list, p, ",")
235
+ for (j = 1; j <= k; j++) if (p[j] == val) return 1
236
+ return 0
237
+ }
238
+ # `allowedImports` is written as path globs in this config ("src/shared/**")
239
+ # but reads naturally as layer names ("domain"). Accept both: a path glob is
240
+ # matched against the resolved target path, a bare identifier against the
241
+ # destination layer name. Supporting only one form silently misreports every
242
+ # edge that used the other, which is how an allow-list turns into a false
243
+ # accusation.
244
+ function allowed_ok(idx, tgt, dstname, k, j, p) {
245
+ k = split(lallow[idx], p, ",")
246
+ for (j = 1; j <= k; j++) {
247
+ if (p[j] == "") continue
248
+ if (p[j] == dstname) return 1
249
+ if (p[j] ~ /[*]/ && tgt ~ pat2re(p[j])) return 1
250
+ if (p[j] !~ /[*]/ && (tgt == p[j] || tgt ~ ("^" p[j] "/"))) return 1
251
+ }
252
+ return 0
253
+ }
254
+ # Resolve a relative specifier against the importing file.
255
+ function resolve(from, spec, np, i, dir, res, k, pp, trail, sx) {
256
+ sub(/[.](ts|tsx|js|jsx|mjs|cjs)$/, "", spec)
257
+ if (spec !~ /^[.][.]?\//) return ""
258
+ np = split(from, sx, "/")
259
+ dir = ""
260
+ for (i = 1; i < np; i++) dir = (dir == "" ? sx[i] : dir "/" sx[i])
261
+ res = dir
262
+ trail = spec
263
+ while (trail ~ /^[.][.]?\//) {
264
+ if (trail ~ /^[.]\//) { trail = substr(trail, 3); continue }
265
+ trail = substr(trail, 4)
266
+ if (res == "") return ""
267
+ k = split(res, pp, "/"); res = ""
268
+ for (i = 1; i < k; i++) res = (res == "" ? pp[i] : res "/" pp[i])
269
+ }
270
+ return (res == "" ? trail : res "/" trail)
271
+ }
272
+ FNR == 1 {
273
+ file = FILENAME
274
+ sub(/^[.][/]/, "", file)
275
+ src = layer_of(file)
276
+ # Classified-file accounting (#REVIEW-R5): a run where the config declares
277
+ # layers but no file matches any of them is indistinguishable from a clean
278
+ # tree, and reporting that as PASS is how "declared but unenforced" survives
279
+ # one level deeper. Count both sides so the verdict can tell them apart.
280
+ seen++
281
+ if (src != 0) classified++
282
+ }
283
+ {
284
+ line = $0
285
+ # Skip whole-line comments only. A trailing-comment strip would eat the
286
+ # // in http:// inside string literals.
287
+ if (line ~ /^[ \t]*(\/\/|[#]|[*]|\/\*)/) next
288
+ rest = line
289
+ while (match(rest, /from[ \t]+"[^"]+"|from[ \t]+\047[^\047]+\047/)) {
290
+ spec = substr(rest, RSTART, RLENGTH)
291
+ sub(/^from[ \t]+["\047]/, "", spec)
292
+ sub(/["\047]$/, "", spec)
293
+ rest = substr(rest, RSTART + RLENGTH)
294
+ if (src == 0 || spec == "") continue
295
+ tgt = resolve(file, spec)
296
+ if (tgt == "") continue
297
+ dst = layer_of(tgt)
298
+ if (dst == 0 || dst == src) continue
299
+ if (allowed_ok(src, tgt, lname[dst])) continue
300
+ printf "%s\t%s\t%s\t%s\n", file, lname[src], lname[dst], tgt
301
+ }
302
+ }
303
+ END {
304
+ # Classified-file counts go to a side file, not stdout: stdout is the
305
+ # findings stream the verdict reads, and mixing a summary line into it would
306
+ # be parsed as a violation.
307
+ if (ENVIRON["XP_LAYER_STATS"]) {
308
+ printf "%d %d\n", seen, classified > ENVIRON["XP_LAYER_STATS"]
309
+ close(ENVIRON["XP_LAYER_STATS"])
310
+ }
311
+ }
312
+ ' $FILE_LIST 2>/dev/null)
313
+ rm -f "$LAYER_TSV_FILE"
314
+
315
+ if [ -s "$LAYER_STATS_FILE" ]; then
316
+ read -r LAYER_CLASSIFIED_FILES LAYER_CLASSIFIED < "$LAYER_STATS_FILE" || true
317
+ fi
318
+ rm -f "$LAYER_STATS_FILE"
319
+ case "$LAYER_CLASSIFIED_FILES" in ''|*[!0-9]*) LAYER_CLASSIFIED_FILES=0 ;; esac
320
+ case "$LAYER_CLASSIFIED" in ''|*[!0-9]*) LAYER_CLASSIFIED=0 ;; esac
321
+
322
+ # ─── 6. Verdict ─────────────────────────────────────────────────────────────
323
+ if [ -z "$FINDINGS" ]; then
324
+ # Zero findings means one of two very different things: every classified file
325
+ # obeyed the rules, or NO FILE was classified at all because the config and the
326
+ # tree disagree. The first is a pass; the second is a config/reality drift and
327
+ # calling it a pass is the "declared but unenforced" defect Gate 6 exists to
328
+ # catch. Tell them apart before saying anything good.
329
+ if [ "$LAYER_CLASSIFIED" -eq 0 ]; then
330
+ _layers_verdict 3 \
331
+ "⚠️ 0 of $LAYER_CLASSIFIED_FILES scanned file(s) match any of the $LAYER_COUNT declared layer(s) — nothing was actually checked." \
332
+ "layer_config_matches_no_files" \
333
+ " Declared patterns are checked against repo-relative paths." \
334
+ " A config for a different layout than this tree will never enforce anything."
335
+ fi
336
+ _layers_verdict 0 \
337
+ "✅ Layer boundaries verified ($LAYER_COUNT layers, $LAYER_CLASSIFIED file(s) classified, 0 violations)." \
338
+ "layers_checked"
339
+ fi
340
+ TOTAL=$(printf '%s\n' "$FINDINGS" | grep -c . || true)
341
+
342
+ # Ratchet: a recorded baseline is a debt ledger, not an amnesty.
343
+ # The comparison lives in its own file rather than inline: three levels of
344
+ # quoting (bash single quotes -> node source -> JSON) is where the tab-in-JSON
345
+ # bug hid, and a baseline that fails to parse must not be read as "no
346
+ # baseline" — that would make a broken ledger look like a fresh start.
347
+ if [ -f "$LAYER_BASELINE" ] && command -v node >/dev/null 2>&1; then
348
+ NEW_FINDINGS=$(printf '%s\n' "$FINDINGS" | node "$(dirname "$0")/lib/layer-baseline.cjs" "$LAYER_BASELINE" 2>/dev/null)
349
+ if [ $? -eq 4 ]; then
350
+ _layers_verdict 2 \
351
+ "❌ BLOCKED - $LAYER_BASELINE exists but cannot be parsed (fail-closed)." \
352
+ "layer_baseline_unreadable"
353
+ fi
354
+ else
355
+ NEW_FINDINGS="$FINDINGS"
356
+ fi
357
+
358
+ NEW_COUNT=$(printf '%s\n' "$NEW_FINDINGS" | grep -c . || true)
359
+
360
+ if [ "$NEW_COUNT" -eq 0 ]; then
361
+ _layers_verdict 3 \
362
+ "⚠️ $TOTAL layer violation(s), all in baseline — no new violations." \
363
+ "layers_checked_baselined"
364
+ fi
365
+
366
+ _layers_say "❌ BLOCKED - $NEW_COUNT new layer violation(s) (of $TOTAL total):"
367
+ printf '%s\n' "$NEW_FINDINGS" | head -10 | while IFS="$(printf '\t')" read -r f s d t; do
368
+ _layers_say " - $f [$s -> $d] imports $t"
369
+ done
370
+ if [ "$NEW_COUNT" -gt 10 ]; then
371
+ _layers_say " ... and $((NEW_COUNT - 10)) more"
372
+ fi
373
+ _layers_say " A layer may import only what its allowedImports lists."
374
+ _layers_say " To accept an existing violation, record it in $LAYER_BASELINE."
375
+ exit 1
package/gate-8.sh CHANGED
@@ -11,6 +11,25 @@
11
11
  2>&1 echo "→ Gate 8: Secret scanning (gitleaks + detect-secrets)..."
12
12
  GATE_8_START=$(gate_start_ms)
13
13
 
14
+ # Temp files created below (the normalized-baseline copy and the hook output)
15
+ # are registered here and removed by this EXIT trap. Installed at FILE scope
16
+ # because a trap body runs at exit time, when a function-local variable is no
17
+ # longer visible — the first cleanup attempt called a function that read a
18
+ # function-local DS_BASELINE and therefore removed nothing.
19
+ #
20
+ # An ARRAY, not a space-separated string: `rm -f $LIST` word-splits, so a
21
+ # TMPDIR containing a space (`/c/Users/Some Name/...` is entirely ordinary on
22
+ # Windows) would be torn into fragments, none of which exist, and every gated
23
+ # commit would leak one temp file again — the exact failure this trap exists to
24
+ # prevent.
25
+ GATE8_TEMP=()
26
+ gate8_cleanup() {
27
+ if [ "${#GATE8_TEMP[@]}" -gt 0 ]; then
28
+ rm -f "${GATE8_TEMP[@]}" 2>/dev/null
29
+ fi
30
+ }
31
+ trap gate8_cleanup EXIT
32
+
14
33
  # Gitleaks availability check
15
34
  GITLEAKS_CMD=""
16
35
  if command -v gitleaks >/dev/null 2>&1; then
@@ -196,35 +215,138 @@ fi
196
215
  # both detect-secrets-hook and .secrets.baseline. The pipeline lives inside an
197
216
  # if-condition (errexit-exempt); a non-zero hook exit lands in the else branch.
198
217
  if command -v detect-secrets-hook >/dev/null 2>&1 && [ -f ".secrets.baseline" ]; then
218
+ # #735: normalize path separators BEFORE comparing against the baseline.
219
+ # detect-secrets writes backslash paths on Windows and forward slashes on
220
+ # Linux, and the baseline is committed, so the two forms fight: a Windows scan
221
+ # rewrites ~322 lines, a Linux run rewrites them back, and every commit
222
+ # carries a pure formatting diff. That destroys the only signal the baseline
223
+ # has - "did a NEW secret appear" - because a real new entry no longer stands
224
+ # out from churn. Normalizing HERE (not only in the repair hint) makes the
225
+ # comparison see one canonical form regardless of which platform last touched
226
+ # the file.
227
+ #
228
+ # Two traps had to be handled, both found by RUNNING it rather than reading it:
229
+ # (1) this script lives at different depths in the source tree
230
+ # (githooks/adapters/) and in the install (~/.config/xp-gate/adapters/), so
231
+ # a fixed ../../ silently resolved to nothing in the installed copy;
232
+ # (2) on Git Bash the resolved path is POSIX-style (/c/Users/...), and handing
233
+ # it to the native node.exe makes MSYS rewrite it into D:\c\Users\... -
234
+ # node then dies with MODULE_NOT_FOUND, which `|| true` swallowed. The
235
+ # gate looked patched and normalised nothing at all.
236
+ # Hence: probe several layouts, then cygpath the winner to a Windows path.
237
+ # Best-effort on purpose - a missing node or unparsable baseline must let the
238
+ # hook speak, never abort the gate silently.
239
+ ds_norm=""
240
+ ds_here="$(dirname "${BASH_SOURCE[0]}")"
241
+ for cand in "$ds_here/../../scripts/normalize-secrets-baseline.cjs" "$ds_here/../scripts/normalize-secrets-baseline.cjs" "$XP_GATE_HOME/scripts/normalize-secrets-baseline.cjs"; do
242
+ if [ -n "$cand" ] && [ -f "$cand" ]; then ds_norm="$cand"; break; fi
243
+ done
244
+ # Normalize a TEMP COPY, never the tracked file.
245
+ #
246
+ # The first version rewrote `.secrets.baseline` in place and did not re-stage
247
+ # it, so the commit still carried the mixed-separator version (#735 relocated
248
+ # rather than resolved) and every gated commit left a tracked file dirty for a
249
+ # reason the user never asked for. Comparing against a normalized copy leaves
250
+ # the working tree untouched and makes the guarantee unconditional: the
251
+ # comparison always sees one canonical form, whether or not the committed
252
+ # baseline is clean.
253
+ DS_BASELINE=".secrets.baseline"
254
+ # Every degradation path below prints WHY, including the two that are not
255
+ # failures: a missing normalizer or a missing node used to fall through in
256
+ # total silence, so the comparison ran on mixed separators and a resulting
257
+ # BLOCK read as "found secrets" with no way to connect it to the real cause.
258
+ # #735 is precisely about that mismatch, so it must never be invisible.
259
+ if [ -z "$ds_norm" ]; then
260
+ echo " ⚠️ baseline normalizer not found (looked next to the hook, in"
261
+ echo " ../scripts and \$XP_GATE_HOME/scripts) — comparing with the"
262
+ echo " committed separators; Windows/Linux baselines may disagree."
263
+ elif ! command -v node >/dev/null 2>&1; then
264
+ echo " ⚠️ node not found — cannot normalize the detect-secrets baseline;"
265
+ echo " comparing with the committed separators."
266
+ else
267
+ ds_norm_arg="$ds_norm"
268
+ if command -v cygpath >/dev/null 2>&1; then
269
+ ds_norm_arg="$(cygpath -w "$ds_norm" 2>/dev/null || printf '%s' "$ds_norm")"
270
+ fi
271
+ # The copy lives next to the original, not in $TMPDIR. Two different path
272
+ # dialects consume this one path: node.exe is native and needs a Windows
273
+ # form, while detect-secrets-hook is a Python script that resolves the path
274
+ # itself and REJECTS the Windows form ("Invalid path"). A bare filename in
275
+ # the current directory is the only spelling both accept, and it is also
276
+ # what `git add`/`git status` see, so the file is unmistakably temporary.
277
+ DS_BASELINE=".secrets.baseline.gate8.$$"
278
+ # Register BEFORE creating it. Registering after a successful `cp` leaves a
279
+ # window in which a signal or an errexit abort between the two lines leaves
280
+ # the copy on disk with nothing tracking it — the trap only removes what it
281
+ # knows about. rm -f on a name that was never created is a no-op, so the
282
+ # early registration costs nothing.
283
+ GATE8_TEMP+=("$DS_BASELINE")
284
+ if ! cp .secrets.baseline "$DS_BASELINE" 2>/dev/null; then
285
+ DS_BASELINE=".secrets.baseline"
286
+ fi
287
+ if [ "$DS_BASELINE" != ".secrets.baseline" ]; then
288
+ # NOT `>/dev/null 2>&1 || true`: that swallowed exit 2 (unparsable JSON)
289
+ # and any runtime throw, so the gate reported a clean comparison while the
290
+ # copy had never been normalized — the same "looked patched, did nothing"
291
+ # shape the path probing above exists to fix. A failure is now VISIBLE.
292
+ # `if !` rather than `cmd; rc=$?` because the enclosing hook may run under
293
+ # errexit, where a bare failing assignment would abort before the message
294
+ # could print.
295
+ if ! ds_norm_out="$(node "$ds_norm_arg" "$DS_BASELINE" 2>&1)"; then
296
+ echo " ⚠️ detect-secrets baseline NOT normalized; comparing with"
297
+ echo " whatever separators the committed file uses. Reason:"
298
+ printf '%s
299
+ ' "$ds_norm_out" | sed 's/^/ /'
300
+ fi
301
+ fi
302
+ fi
303
+ # The normalized copy and the hook output are both temp files. The first
304
+ # version of this block removed neither DS_BASELINE (leaked one copy PER
305
+ # gated commit) nor DS_TMP on the early `exit 1` paths. They are registered in
306
+ # the global GATE8_TEMP list, which the EXIT trap installed at the top of this
307
+ # file cleans up — a trap calling a function that reads a FUNCTION-LOCAL
308
+ # variable sees an empty value at exit time, which is exactly how the first
309
+ # fix attempt silently cleaned nothing.
199
310
  DS_TMP="$(dirname "$(mktemp -u)")/ds-output.$$"
311
+ GATE8_TEMP+=("$DS_TMP")
200
312
  # #616: same scope split as the gitleaks call above. Under `--all` the index is
201
313
  # usually empty, so piping `git diff --cached -z` into xargs fed the hook zero
202
314
  # files and it reported success without reading anything.
203
315
  if [ "${GATE_SCOPE:-diff}" = "all" ]; then
204
- if git ls-files -z | xargs -0 detect-secrets-hook --baseline .secrets.baseline > "$DS_TMP" 2>&1; then
316
+ if git ls-files -z | xargs -0 detect-secrets-hook --baseline "$DS_BASELINE" > "$DS_TMP" 2>&1; then
205
317
  echo " ✅ detect-secrets PASSED - no new secrets beyond baseline (scope: --all)."
206
318
  else
207
319
  cat "$DS_TMP"
208
320
  echo ""
209
321
  echo " ❌ BLOCKED - detect-secrets found secrets not in .secrets.baseline."
210
- echo " If these are false positives, regenerate the baseline (cross-platform):"
211
- echo " detect-secrets scan --update .secrets.baseline && git add .secrets.baseline"
212
- rm -f "$DS_TMP"
322
+ echo " If these are false positives, mark them in the baseline:"
323
+ echo " detect-secrets scan --baseline .secrets.baseline && git add .secrets.baseline"
324
+ echo " (--update does not exist; detect-secrets exits with"
325
+ echo " \"unrecognized arguments: --update\".)"
326
+ echo " Then REVIEW the diff: scan --baseline re-scans the WHOLE tree, whereas"
327
+ echo " this gate only inspects changed files. A whole-tree scan can silently"
328
+ echo " drop the entries of files it no longer reaches, un-allowlisting a"
329
+ echo " historical finding. Commit the baseline alone so that stays visible."
213
330
  exit 1
214
331
  fi
215
332
  elif git diff --cached --name-only --diff-filter=ACM -z \
216
- | xargs -0 detect-secrets-hook --baseline .secrets.baseline > "$DS_TMP" 2>&1; then
333
+ | xargs -0 detect-secrets-hook --baseline "$DS_BASELINE" > "$DS_TMP" 2>&1; then
217
334
  echo " ✅ detect-secrets PASSED - no new secrets beyond baseline."
218
335
  else
219
336
  cat "$DS_TMP"
220
337
  echo ""
221
338
  echo " ❌ BLOCKED - detect-secrets found secrets not in .secrets.baseline."
222
- echo " If these are false positives, regenerate the baseline (cross-platform):"
223
- echo " detect-secrets scan --update .secrets.baseline && git add .secrets.baseline"
224
- rm -f "$DS_TMP"
339
+ echo " If these are false positives, mark them in the baseline:"
340
+ echo " detect-secrets scan --baseline .secrets.baseline && git add .secrets.baseline"
341
+ echo " (--update does not exist; detect-secrets exits with"
342
+ echo " \"unrecognized arguments: --update\".)"
343
+ echo " Then REVIEW the diff: scan --baseline re-scans the WHOLE tree, whereas"
344
+ echo " this gate only inspects changed files. A whole-tree scan can silently"
345
+ echo " drop the entries of files it no longer reaches, un-allowlisting a"
346
+ echo " historical finding. Commit the baseline alone so that stays visible."
225
347
  exit 1
226
348
  fi
227
- rm -f "$DS_TMP"
349
+ # Temp cleanup is owned by the gate8_cleanup trap; no rm here.
228
350
  else
229
351
  echo " ⚠️ detect-secrets-hook unavailable (install: pip install -e \".[dev]\") — gitleaks only."
230
352
  fi
package/hooks/gate-10.sh CHANGED
@@ -28,6 +28,72 @@ GATE_10_REASON=""
28
28
  # shellcheck disable=SC2034
29
29
  GATE_10_SCANNED_FILES=0
30
30
 
31
+ # ---------------------------------------------------------------------------
32
+ # Which path runs semgrep: the sastd daemon (fast) or a direct invocation.
33
+ #
34
+ # A direct `semgrep scan` costs ~9s on Windows, and the bill is almost entirely
35
+ # Python import tax: `--version` alone takes 4-5s because semgrep's CLI eagerly
36
+ # imports commands.ci -> app.auth -> telemetry -> opentelemetry -> requests ->
37
+ # urllib3. Paying that once per machine in a resident process is the point of
38
+ # sastd (measured: a second in-process import costs 0ms).
39
+ #
40
+ # GATE_10_SEMGREP_PATH records what actually happened, so a reader of the report
41
+ # can tell a fast run from a degraded one without timing it.
42
+ #
43
+ # The daemon does not exist yet (that is E2/E3). Until it does, EVERY value of
44
+ # XP_GATE_SASTD resolves to "direct", which is what makes shipping E1 a no-op:
45
+ # the switch, the degrade flag and the tests land first so the fast path is added
46
+ # onto a base that is already proven to behave exactly as today.
47
+ # ---------------------------------------------------------------------------
48
+ # Consumed by the sourcing parent (pre-commit report JSON), not here.
49
+ # shellcheck disable=SC2034
50
+ GATE_10_SEMGREP_PATH="direct"
51
+ # Set to 1 when sastd was requested but unusable, so "we fell back" is a fact in
52
+ # the report rather than an inference from a missing log line. Never set when the
53
+ # daemon was not requested at all -- a plain direct run is not a degraded run.
54
+ # Consumed by the sourcing parent (pre-commit report JSON), not here.
55
+ # shellcheck disable=SC2034
56
+ GATE_10_SASTD_DEGRADED=0
57
+
58
+ # shellcheck disable=SC2034
59
+ case "${XP_GATE_SASTD:-direct}" in
60
+ off|direct|0|false|"")
61
+ # Explicitly or implicitly off: the direct path. Not a degradation.
62
+ GATE_10_SEMGREP_PATH="direct"
63
+ ;;
64
+ auto)
65
+ # "Use the daemon if one is available, otherwise just scan." Absence of a
66
+ # daemon is the normal state for most users, not a fault, so `auto` does NOT
67
+ # set the degraded flag -- marking it would make every ordinary run look
68
+ # degraded the moment E2 lands and train readers to ignore the flag.
69
+ # E2 MUST add a probe INSIDE this branch rather than flipping the value:
70
+ # a daemon that is ABSENT keeps degraded=0 (normal), but a daemon that is
71
+ # PRESENT BUT UNUSABLE must set degraded=1 -- otherwise `auto` silently
72
+ # swallows the same failure `on` reports. Get that distinction right here;
73
+ # it is the whole reason the two branches are separate.
74
+ GATE_10_SEMGREP_PATH="direct"
75
+ ;;
76
+ on|1|true)
77
+ # The user asserted a daemon SHOULD be here. If it is not, that is a
78
+ # degradation worth reporting: their configuration is not being honoured.
79
+ # This is the branch that must never become "skip the scan and call it a pass".
80
+ GATE_10_SEMGREP_PATH="direct"
81
+ GATE_10_SASTD_DEGRADED=1
82
+ # stderr, not stdout: this file is SOURCED by pre-commit, so stdout belongs to
83
+ # the parent's report stream. A notice written there would land inside output
84
+ # that another consumer may parse. stderr still reaches the developer's
85
+ # terminal, which is the only audience a notice needs.
86
+ echo " ℹ️ sastd requested but not available — using direct semgrep (degraded)" >&2
87
+ ;;
88
+ *)
89
+ # An unrecognised value is a configuration mistake, not a reason to scan
90
+ # less. Use the direct path and name the value so it can be fixed.
91
+ GATE_10_SEMGREP_PATH="direct"
92
+ GATE_10_SASTD_DEGRADED=1
93
+ echo " ⚠️ XP_GATE_SASTD='${XP_GATE_SASTD}' is not recognised (expected off|auto|on) — using direct semgrep" >&2
94
+ ;;
95
+ esac
96
+
31
97
  # Semgrep availability check
32
98
  SEMGREP_CMD=""
33
99
  if command -v semgrep >/dev/null 2>&1; then
@@ -86,6 +86,19 @@ if [ -n "$TRAILING_WS_FILES" ]; then
86
86
  fi
87
87
 
88
88
  # --- Check 2: Missing EOF newline ---
89
+ # Reads the LAST BYTE from the raw blob. The previous form captured the content
90
+ # with $(...) and then asked for its final character: command substitution
91
+ # strips every trailing newline, so a file that ends correctly produced its last
92
+ # visible character — never empty — and was reported as missing its newline.
93
+ # Every staged text file was a false positive, which is how a check that always
94
+ # fires looks exactly like a strict check. `git show | tail -c 1` keeps the byte.
95
+ file_missing_eof_newline() {
96
+ local last_byte
97
+ last_byte=$(git show ":$1" 2>/dev/null | tail -c 1)
98
+ # Empty output means the blob is empty: there is no line to terminate.
99
+ [ -n "$last_byte" ]
100
+ }
101
+
89
102
  NO_EOF_NEWLINE_FILES=""
90
103
  if [ "${GATE_12_DOCS_ONLY:-false}" != true ]; then
91
104
  while IFS= read -r file; do
@@ -94,13 +107,8 @@ while IFS= read -r file; do
94
107
  if is_binary_staged_file "$file"; then
95
108
  continue
96
109
  fi
97
- # Check if file content ends with newline
98
- FILE_CONTENT=$(git show ":$file" 2>/dev/null)
99
- if [ -n "$FILE_CONTENT" ]; then
100
- LAST_CHAR=$(printf '%s' "$FILE_CONTENT" | tail -c 1)
101
- if [ "$LAST_CHAR" != "" ]; then
102
- NO_EOF_NEWLINE_FILES="$NO_EOF_NEWLINE_FILES $file"
103
- fi
110
+ if file_missing_eof_newline "$file"; then
111
+ NO_EOF_NEWLINE_FILES="$NO_EOF_NEWLINE_FILES $file"
104
112
  fi
105
113
  done <<EOF
106
114
  $STAGED_FILES