@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
@@ -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
package/hooks/gate-3.sh CHANGED
@@ -350,7 +350,7 @@ else
350
350
  }
351
351
 
352
352
  CCN_THRESHOLD=$(resolve_ccn_threshold)
353
-
353
+
354
354
  # Check lizard availability
355
355
  LIZARD_CMD=""
356
356
  if command -v lizard > /dev/null 2>&1; then
@@ -358,10 +358,10 @@ else
358
358
  elif [ -f ~/.local/bin/lizard ]; then
359
359
  LIZARD_CMD=~/.local/bin/lizard
360
360
  fi
361
-
361
+
362
362
  if [ -n "$LIZARD_CMD" ]; then
363
363
  LIZARD_PATH=$(eval echo "$LIZARD_CMD")
364
-
364
+
365
365
  # Get changed source files for complexity check (includes test files)
366
366
  CC_FILES=$(echo "$CHANGED_FILES" | grep -E '\.(ts|tsx|js|jsx|py|go|java|swift|cpp|c|hpp|h|m|mm|kt|cs)$' || true)
367
367
 
@@ -398,7 +398,7 @@ else
398
398
 
399
399
  if [ -n "$CC_FILES" ]; then
400
400
  echo "Checking complexity for source files..."
401
-
401
+
402
402
  # Run lizard in chunks. Two reasons, both load-bearing:
403
403
  # - One path per line, into an array. Unquoted $CC_FILES relied on word
404
404
  # splitting, which also splits any path containing a space -- handing
@@ -595,7 +595,17 @@ CC_POP_EOF
595
595
  # contain a function. If it produces rows, lizard works and the input
596
596
  # simply had no functions (SKIP, `no_functions_in_input`); if it does not,
597
597
  # the tool really is broken (WARN, `lizard_output_unparsable`).
598
- if ! printf '%s\n' "$CC_CSV_FLAT" | awk -F, 'NF > 1 && $2 ~ /^[0-9]+$/ { found = 1; exit }
598
+ #
599
+ # #774: the probe must read the WHOLE stream. It used to `exit` on the
600
+ # first matching row, which left `printf` writing into a closed pipe; under
601
+ # the hook's `set -o pipefail` the pipeline then reported SIGPIPE (141)
602
+ # instead of awk's 0, and a run with 26 above-threshold functions announced
603
+ # itself as "no functions (pure data module)". Measured: the flip happens
604
+ # once the CSV exceeds the 64 KB pipe buffer -- 24 changed source files were
605
+ # enough -- and it is timing-dependent, so the same commit could pass or
606
+ # skip. Counting through to END also drops the dependency on how much stdin
607
+ # happened to be buffered.
608
+ if ! printf '%s\n' "$CC_CSV_FLAT" | awk -F, 'NF > 1 && $2 ~ /^[0-9]+$/ { found = 1 }
599
609
  END { exit(found ? 0 : 1) }'; then
600
610
  _lizard_probe_dir=$(mktemp -d 2>/dev/null || echo "${TMPDIR:-/tmp}")
601
611
  _lizard_probe_file="$_lizard_probe_dir/xp-gate-lizard-probe.py"
@@ -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