@boyingliu01/xp-gate 0.37.0 → 0.37.2

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 (60) hide show
  1. package/adapters/typescript.sh +11 -1
  2. package/gate-10.sh +66 -0
  3. package/gate-13-compiler-strictness.sh +81 -1
  4. package/gate-6-layers.sh +375 -0
  5. package/hooks/gate-10.sh +66 -0
  6. package/hooks/gate-13-compiler-strictness.sh +81 -1
  7. package/hooks/gate-6-layers.sh +375 -0
  8. package/hooks/gate-registry.sh +2 -2
  9. package/hooks/hook-module-resolution.sh +1 -1
  10. package/hooks/lib/layer-baseline.cjs +88 -0
  11. package/hooks/lib/typecheck.sh +28 -5
  12. package/hooks/pre-commit +96 -11
  13. package/lib/__tests__/detect-deps-gate-identity.test.js +135 -0
  14. package/lib/__tests__/doctor-drift-round2.test.js +4 -1
  15. package/lib/__tests__/doctor-executed-surface.test.js +45 -24
  16. package/lib/__tests__/doctor-module-drift.test.js +13 -7
  17. package/lib/__tests__/doctor-module-resolution-parity.test.js +74 -2
  18. package/lib/__tests__/doctor.test.js +17 -0
  19. package/lib/__tests__/gate-runner-tsx-invocation.test.js +149 -0
  20. package/lib/__tests__/gate-runner.test.js +23 -7
  21. package/lib/__tests__/phase-transition.test.js +19 -1
  22. package/lib/__tests__/sprint-status-rework.test.js +32 -12
  23. package/lib/detect-deps.js +7 -1
  24. package/lib/doctor.js +81 -17
  25. package/lib/gate-runner.js +101 -7
  26. package/lib/hook-module-resolution.js +18 -6
  27. package/lib/layer-baseline.cjs +88 -0
  28. package/lib/mattpocock-license-verdict.json +1 -1
  29. package/mock-policy/AGENTS.md +1 -1
  30. package/mutation/AGENTS.md +1 -1
  31. package/package.json +2 -1
  32. package/plugins/claude-code/.claude-plugin/plugin.json +1 -1
  33. package/plugins/claude-code/skills/delphi-review/AGENTS.md +1 -1
  34. package/plugins/claude-code/skills/sprint-flow/AGENTS.md +1 -1
  35. package/plugins/claude-code/skills/sprint-flow/references/phase-5-ship.md +6 -2
  36. package/plugins/claude-code/skills/test-specification-alignment/AGENTS.md +1 -1
  37. package/plugins/dsh/package.json +1 -1
  38. package/plugins/dsh/skills/delphi-review/AGENTS.md +1 -1
  39. package/plugins/dsh/skills/sprint-flow/AGENTS.md +1 -1
  40. package/plugins/dsh/skills/sprint-flow/references/phase-5-ship.md +6 -2
  41. package/plugins/dsh/skills/test-specification-alignment/AGENTS.md +1 -1
  42. package/plugins/opencode/package.json +1 -1
  43. package/plugins/opencode/skills/delphi-review/AGENTS.md +1 -1
  44. package/plugins/opencode/skills/sprint-flow/AGENTS.md +1 -1
  45. package/plugins/opencode/skills/sprint-flow/references/phase-5-ship.md +6 -2
  46. package/plugins/opencode/skills/test-specification-alignment/AGENTS.md +1 -1
  47. package/plugins/qoder/plugin.json +1 -1
  48. package/plugins/qoder/skills/delphi-review/AGENTS.md +1 -1
  49. package/plugins/qoder/skills/sprint-flow/AGENTS.md +1 -1
  50. package/plugins/qoder/skills/sprint-flow/references/phase-5-ship.md +6 -2
  51. package/plugins/qoder/skills/test-specification-alignment/AGENTS.md +1 -1
  52. package/principles/AGENTS.md +1 -1
  53. package/principles/adapters/csharp.ts +73 -42
  54. package/principles/adapters/java.ts +9 -5
  55. package/principles/adapters/typescript.ts +130 -45
  56. package/principles/index.ts +30 -14
  57. package/skills/delphi-review/AGENTS.md +1 -1
  58. package/skills/sprint-flow/AGENTS.md +1 -1
  59. package/skills/sprint-flow/references/phase-5-ship.md +6 -2
  60. package/skills/test-specification-alignment/AGENTS.md +1 -1
@@ -33,8 +33,18 @@ run_lint() {
33
33
  # Prefer Biome if biome.json/biome.jsonc exists (covers lint + format in one pass)
34
34
  if [ -f "biome.json" ] || [ -f "biome.jsonc" ]; then
35
35
  echo "Running Biome linting..."
36
- npx biome check . --no-errors-on-unmatched 2>&1 | head -50
36
+ # `$?` here is Biome's, and it has to be: this used to read
37
+ # npx biome check . 2>&1 | head -50
38
+ # local EXIT_CODE=$?
39
+ # and in a POSIX pipeline `$?` is the status of the LAST command -- `head` --
40
+ # so it was always 0. The failure branch below could never run and a project
41
+ # with Biome errors was told "PASSED". Capture the status first, then trim
42
+ # the output. This repo has no biome.json so its own commits never showed it;
43
+ # every downstream project using Biome was affected (#437).
44
+ local BIOME_OUTPUT
45
+ BIOME_OUTPUT=$(npx biome check . --no-errors-on-unmatched 2>&1)
37
46
  local EXIT_CODE=$?
47
+ printf '%s\n' "$BIOME_OUTPUT" | head -50
38
48
  if [ $EXIT_CODE -ne 0 ]; then
39
49
  echo ""
40
50
  echo "❌ Biome check failed"
package/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
@@ -1201,6 +1201,79 @@ EOF
1201
1201
  # detection and gates drift apart.
1202
1202
  # ============================================================================
1203
1203
 
1204
+ # The strictness flag set for C#, decided by tier.
1205
+ #
1206
+ # Why this exists: unlike the C/C++/Java paths, the C# path used to run a bare
1207
+ # `dotnet build`, which inherits whatever the project happens to declare. A
1208
+ # project with `<TreatWarningsAsErrors>false</TreatWarningsAsErrors>` -- or one
1209
+ # that simply never set it, which is the common case -- sailed through with real
1210
+ # warnings. Measured on a fixture holding an unused field and an instance method
1211
+ # that could be static: "1 warning, 0 errors, build succeeded". The gate saw a
1212
+ # warning it could not act on, because it decides BLOCK from the build's exit
1213
+ # code. A strictness gate that depends on the audited project having declared
1214
+ # strictness is not a gate; it is a mirror.
1215
+ #
1216
+ # Passing these on the command line overrides the project-level properties --
1217
+ # measured: a project declaring TreatWarningsAsErrors=false still failed the
1218
+ # build once -warnaserror was passed. So this does not force downstream projects
1219
+ # to edit their own files.
1220
+ #
1221
+ # DELIBERATELY NOT INCLUDED -- these change compilation semantics rather than
1222
+ # raising the bar on existing code, and the C/C++/Java paths have no equivalent:
1223
+ #
1224
+ # -p:Nullable=enable
1225
+ # Turns on nullable *reference type* analysis, i.e. it opts the project
1226
+ # into a language feature it never asked for. Measured: a project without
1227
+ # it reports CS8632 ("nullable reference types only inside #nullable
1228
+ # context"); with it, the same line becomes CS8603 (possible null return).
1229
+ # Gating a legacy codebase on warnings it cannot even parse today is
1230
+ # exactly the false-BLOCK this gate must not produce.
1231
+ #
1232
+ # -p:EnforceCodeStyleInBuild=true
1233
+ # Measured to emit ZERO IDE diagnostics on a project with no .editorconfig
1234
+ # and no explicit analyzer reference -- it only amplifies configuration the
1235
+ # project already has, so it contributes nothing for the projects that most
1236
+ # need the gate and is a no-op for the rest.
1237
+ #
1238
+ # Tiers mirror the C++/Java paths:
1239
+ # balanced (default) -- warnings are errors at the highest meaningful warning
1240
+ # level, with the recommended analyzer set.
1241
+ # strict -- balanced plus every rule that is only suggestion/hidden
1242
+ # by default promoted via AnalysisMode. Measured to add
1243
+ # CA1707 (identifier contains underscore), which balanced
1244
+ # does not report at all.
1245
+ # warn-only -- no promotion (the caller downgrades the verdict to WARN
1246
+ # on its own, so an empty flag set is correct here).
1247
+ #
1248
+ # ANALYSISLEVEL IS NOT REDUNDANT with -warnaserror: the latter only promotes
1249
+ # compiler diagnostics (CS*), while analyzer rules (CA*) take their severity from
1250
+ # AnalysisLevel. Measured on the fixture above: -warnaserror alone caught CS0414
1251
+ # only; adding AnalysisLevel also caught CA1822. Passing one without the other
1252
+ # blocks half of what this gate is for.
1253
+ #
1254
+ # WARNINGLEVEL=9999 is intentional and safe: csc accepts /warn:N for N > 4 --
1255
+ # measured /warn:4, /warn:9, /warn:100, /warn:9999 and /warn:999999 all compile
1256
+ # identically with no CS1900. Only /warn:0 suppresses; there is no upper bound.
1257
+ # 9999 is used instead of 4 so that any warning level a future SDK introduces is
1258
+ # covered without this file needing a change.
1259
+ gate13_csharp_flags() {
1260
+ local tier="${1:-balanced}"
1261
+
1262
+ if [ "$tier" = "warn-only" ]; then
1263
+ printf '%s\n' ""
1264
+ return 0
1265
+ fi
1266
+
1267
+ local base="-warnaserror -p:WarningLevel=9999 -p:AnalysisLevel=latest-recommended"
1268
+
1269
+ if [ "$tier" = "strict" ]; then
1270
+ printf '%s %s\n' "$base" "-p:AnalysisMode=AllEnabledByDefault"
1271
+ return 0
1272
+ fi
1273
+
1274
+ printf '%s\n' "$base"
1275
+ }
1276
+
1204
1277
  # Locate the .NET SDK exactly as adapters/csharp.sh does.
1205
1278
  gate13_csharp_dotnet() {
1206
1279
  local d
@@ -1280,7 +1353,14 @@ gate13_csharp_changed_warning_count() {
1280
1353
  # dies with MSB1003 whenever the project sits in a subdirectory, emitting no
1281
1354
  # diagnostics at all.
1282
1355
  entry=$(gate13_csharp_entry_point) || return 1
1283
- out=$("$dotnet" build "$entry" --nologo --no-incremental -clp:NoSummary 2>&1)
1356
+
1357
+ # Strictness flags come from OUTSIDE the project, so the gate does not depend
1358
+ # on the audited repository having declared them. Empty in the warn-only tier.
1359
+ local flags
1360
+ flags=$(gate13_csharp_flags "$(gate13_resolve_tier)")
1361
+
1362
+ # shellcheck disable=SC2086 # $flags is a deliberately word-split flag list
1363
+ out=$("$dotnet" build "$entry" --nologo --no-incremental -clp:NoSummary $flags 2>&1)
1284
1364
 
1285
1365
  # Report distinct CHANGED FILES, not diagnostic instances: the caller speaks in
1286
1366
  # files ("N changed C# file(s) carry compiler warnings"), and one file with two
@@ -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/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