@boyingliu01/xp-gate 0.37.0 → 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 (55) 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/test-specification-alignment/AGENTS.md +1 -1
  36. package/plugins/dsh/package.json +1 -1
  37. package/plugins/dsh/skills/delphi-review/AGENTS.md +1 -1
  38. package/plugins/dsh/skills/sprint-flow/AGENTS.md +1 -1
  39. package/plugins/dsh/skills/test-specification-alignment/AGENTS.md +1 -1
  40. package/plugins/opencode/package.json +1 -1
  41. package/plugins/opencode/skills/delphi-review/AGENTS.md +1 -1
  42. package/plugins/opencode/skills/sprint-flow/AGENTS.md +1 -1
  43. package/plugins/opencode/skills/test-specification-alignment/AGENTS.md +1 -1
  44. package/plugins/qoder/plugin.json +1 -1
  45. package/plugins/qoder/skills/delphi-review/AGENTS.md +1 -1
  46. package/plugins/qoder/skills/sprint-flow/AGENTS.md +1 -1
  47. package/plugins/qoder/skills/test-specification-alignment/AGENTS.md +1 -1
  48. package/principles/AGENTS.md +1 -1
  49. package/principles/adapters/csharp.ts +73 -42
  50. package/principles/adapters/java.ts +9 -5
  51. package/principles/adapters/typescript.ts +130 -45
  52. package/principles/index.ts +30 -14
  53. package/skills/delphi-review/AGENTS.md +1 -1
  54. package/skills/sprint-flow/AGENTS.md +1 -1
  55. 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
@@ -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
@@ -50,7 +50,7 @@
50
50
  # name|number|impl|blocks
51
51
  GATE_REGISTRY_ROWS=(
52
52
  "version-consistency|0|inline|YES"
53
- "code-quality|1|inline|NO"
53
+ "code-quality|1|inline|YES"
54
54
  "duplicate-code|2|inline|NO"
55
55
  "complexity|3|gate-3.sh|YES"
56
56
  "principles|4|gate-4.sh|YES"
@@ -58,7 +58,7 @@ GATE_REGISTRY_ROWS=(
58
58
  "architecture|6|inline|YES"
59
59
  "iac-security|7|gate-7.sh|YES"
60
60
  "secret-scanning|8|gate-8.sh|YES"
61
- "build-integrity|9|inline|NO"
61
+ "build-integrity|9|inline|YES"
62
62
  "sast|10|gate-10.sh|YES"
63
63
  "sprint-flow|11|sprint-gate.sh|YES"
64
64
  "file-hygiene|12|gate-12-file-hygiene.sh|NO"
@@ -24,8 +24,8 @@ HOOK_GATE_PROBE="gate-3.sh"
24
24
  # Consumed by the sourcing parent, not here.
25
25
  # shellcheck disable=SC2034
26
26
  HOOK_ADAPTER_DIR_TIERS=(
27
- 'global|GLOBAL_ADAPTER_DIR|adapter-common.sh'
28
27
  'project|PROJECT_GITHOOKS|adapter-common.sh'
28
+ 'global|GLOBAL_ADAPTER_DIR|adapter-common.sh'
29
29
  'script|SCRIPT_DIR|adapter-common.sh'
30
30
  )
31
31
 
@@ -0,0 +1,88 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * Layer-baseline comparison for Gate 6's layer check.
4
+ *
5
+ * Reads findings on stdin (one per line, fields separated by real TABs) and a
6
+ * JSON ledger as argv[2], and writes the findings that are NOT in the ledger.
7
+ *
8
+ * Exit 4 when the ledger exists but cannot be parsed. The caller treats that as
9
+ * BLOCK (fail-closed): a ledger that silently reads as empty would turn every
10
+ * accepted violation back into a new one, and the next natural response — re-run
11
+ * with a bigger baseline — quietly launders the debt.
12
+ *
13
+ * Why this is a file and not an inline `node -e`: the first version embedded
14
+ * this in bash single quotes, and the TAB separators ended up inside a JSON
15
+ * string literal, which JSON.parse rejects (raw control character). The error
16
+ * was then swallowed by `2>/dev/null`, so the ratchet silently reset on every
17
+ * run. Three levels of quoting is where that hid; one level is enough.
18
+ *
19
+ * Ledger shape:
20
+ * { "accepted": [ { "file", "from", "to", "imports" }, ... ] }
21
+ *
22
+ * A plain tab-joined string is also accepted for entries, so hand-written and
23
+ * generated ledgers both work.
24
+ */
25
+
26
+ 'use strict';
27
+
28
+ const fs = require('fs');
29
+
30
+ const SEVERITY_EXIT_UNREADABLE = 4;
31
+
32
+ /** Normalise one ledger entry to the tab-joined form used on stdin. */
33
+ function toKey(entry) {
34
+ if (typeof entry === 'string') {
35
+ return entry;
36
+ }
37
+ if (entry && typeof entry === 'object') {
38
+ return [entry.file, entry.from, entry.to, entry.imports].join('\t');
39
+ }
40
+ return '';
41
+ }
42
+
43
+ /** Read and validate the ledger. Throws when it cannot be used. */
44
+ function readLedger(path) {
45
+ const raw = fs.readFileSync(path, 'utf8');
46
+ const parsed = JSON.parse(raw);
47
+ const accepted = Array.isArray(parsed.accepted) ? parsed.accepted : [];
48
+ return new Set(accepted.map(toKey).filter(Boolean));
49
+ }
50
+
51
+ /** Split stdin into findings and drop the baselined ones. */
52
+ function filterFindings(raw, known) {
53
+ return raw
54
+ .split('\n')
55
+ .filter(Boolean)
56
+ .filter(line => !known.has(line));
57
+ }
58
+
59
+ function main() {
60
+ const ledgerPath = process.argv[2];
61
+ if (!ledgerPath) {
62
+ process.stderr.write('usage: layer-baseline.cjs <ledger.json> < findings\n');
63
+ process.exit(SEVERITY_EXIT_UNREADABLE);
64
+ return;
65
+ }
66
+
67
+ let known;
68
+ try {
69
+ known = readLedger(ledgerPath);
70
+ } catch (err) {
71
+ process.stderr.write(`layer-baseline unreadable: ${err.message}\n`);
72
+ process.exit(SEVERITY_EXIT_UNREADABLE);
73
+ return;
74
+ }
75
+
76
+ let raw = '';
77
+ process.stdin.setEncoding('utf8');
78
+ process.stdin.on('data', chunk => {
79
+ raw += chunk;
80
+ });
81
+ process.stdin.on('end', () => {
82
+ process.stdout.write(filterFindings(raw, known).join('\n'));
83
+ });
84
+ }
85
+
86
+ main();
87
+
88
+ module.exports = { toKey, readLedger, filterFindings };
@@ -56,12 +56,35 @@ resolve_typecheck_command() {
56
56
  return 0
57
57
  }
58
58
 
59
+ # Runs tsc, preferring the locally installed compiler over npx.
60
+ #
61
+ # `npx tsc --version` measured 1941 ms here against 234 ms for
62
+ # `node node_modules/typescript/bin/tsc --version` -- identical output, 1.7 s of
63
+ # package resolution in between. typecheck.sh called `npx tsc` at five sites and
64
+ # a single commit reaches several of them, so the whole typecheck half of Gate 1
65
+ # paid that toll repeatedly. pre-commit:4324-4345 already made exactly this
66
+ # change for archlint ("measured: 1909 ms via npx vs 319 ms direct"); typecheck
67
+ # never got it.
68
+ #
69
+ # npx stays as the fallback so a consumer repo with no local install behaves
70
+ # exactly as before. Nothing is cached: resolving a path is a couple of `test -f`
71
+ # calls, and a cache would have to be invalidated whenever node_modules changes.
72
+ _tsc_command() {
73
+ if [ -f "node_modules/typescript/bin/tsc" ] && command -v node >/dev/null 2>&1; then
74
+ node "node_modules/typescript/bin/tsc" "$@"
75
+ return $?
76
+ fi
77
+ # The fallback stays a real `npx` call. Rewording this line into a recursive
78
+ # _tsc_command call is a stack overflow, not a fallback.
79
+ npx tsc "$@"
80
+ }
81
+
59
82
  # The #293 extra pass: projects commonly exclude test files from tsconfig.json, so
60
83
  # their type errors accumulate silently. Only meaningful for the tsc fallback —
61
84
  # a project checker covers the files its own config declares.
62
85
  run_test_file_pass() {
63
86
  local has_tests_in_tsc=false
64
- if npx tsc --noEmit --skipLibCheck --listFiles 2>/dev/null | grep -qE '__tests__/|\.test\.ts|\.spec\.ts'; then
87
+ if _tsc_command --noEmit --skipLibCheck --listFiles 2>/dev/null | grep -qE '__tests__/|\.test\.ts|\.spec\.ts'; then
65
88
  has_tests_in_tsc=true
66
89
  fi
67
90
  [ "$has_tests_in_tsc" = false ] || return 0
@@ -69,7 +92,7 @@ run_test_file_pass() {
69
92
  local test_pass_exit=0
70
93
  if [ -f "tsconfig.tests.json" ]; then
71
94
  echo "Checking test files with tsconfig.tests.json..."
72
- npx tsc --noEmit --project tsconfig.tests.json 2>&1 | head -30
95
+ _tsc_command --noEmit --project tsconfig.tests.json 2>&1 | head -30
73
96
  test_pass_exit=${PIPESTATUS[0]}
74
97
  else
75
98
  echo "Checking test files for type errors..."
@@ -81,7 +104,7 @@ run_test_file_pass() {
81
104
  cfg.include.push('src/**/__tests__/**','src/**/*.test.ts','src/**/*.spec.ts');
82
105
  require('fs').writeFileSync('$temp_tsconfig', JSON.stringify(cfg, null, 2));
83
106
  " 2>/dev/null
84
- npx tsc --noEmit --project "$temp_tsconfig" --skipLibCheck 2>&1 | head -30
107
+ _tsc_command --noEmit --project "$temp_tsconfig" --skipLibCheck 2>&1 | head -30
85
108
  test_pass_exit=${PIPESTATUS[0]}
86
109
  rm -f "$temp_tsconfig"
87
110
  fi
@@ -122,7 +145,7 @@ run_typescript_typecheck() {
122
145
 
123
146
  # Verify tsc is the real compiler (npx may fetch the deprecated tsc@2.0.4 placeholder).
124
147
  local tsc_version
125
- tsc_version=$(npx tsc --version 2>&1)
148
+ tsc_version=$(_tsc_command --version 2>&1)
126
149
  if ! echo "$tsc_version" | grep -q "Version"; then
127
150
  echo "ℹ️ SKIP - tsc not properly installed ($tsc_version)"
128
151
  echo "Install typescript (npm install typescript --save-dev) for type checking."
@@ -135,7 +158,7 @@ run_typescript_typecheck() {
135
158
  fi
136
159
 
137
160
  echo "Running TypeScript static analysis ($tsc_version)..."
138
- npx tsc --noEmit --skipLibCheck 2>&1 | head -30
161
+ _tsc_command --noEmit --skipLibCheck 2>&1 | head -30
139
162
  if [ "${PIPESTATUS[0]}" -ne 0 ]; then
140
163
  echo ""
141
164
  echo "❌ BLOCKED - TYPE ERRORS detected"