@boyingliu01/xp-gate 0.38.8 → 0.38.10

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 (48) hide show
  1. package/adapters/shell.sh +87 -2
  2. package/hooks/gate-entries/gate-0-entry.sh +48 -3
  3. package/hooks/gate-entries/gate-12-entry.sh +20 -1
  4. package/hooks/gate-entries/gate-5-entry.sh +56 -2
  5. package/hooks/pre-commit +40 -0
  6. package/lib/mattpocock-license-verdict.json +1 -1
  7. package/mock-policy/AGENTS.md +85 -83
  8. package/mutation/AGENTS.md +87 -61
  9. package/package.json +1 -1
  10. package/plugins/claude-code/.claude-plugin/plugin.json +1 -1
  11. package/plugins/claude-code/skills/delphi-review/AGENTS.md +1 -1
  12. package/plugins/claude-code/skills/ralph-loop/SKILL.md +1 -1
  13. package/plugins/claude-code/skills/ralph-loop/references/components.md +1 -1
  14. package/plugins/claude-code/skills/sprint-flow/AGENTS.md +3 -3
  15. package/plugins/claude-code/skills/sprint-flow/__tests__/sprint-flow.test.cjs +25 -7
  16. package/plugins/claude-code/skills/sprint-flow/references/phase-overview.md +3 -3
  17. package/plugins/claude-code/skills/test-specification-alignment/AGENTS.md +1 -1
  18. package/plugins/dsh/package.json +1 -1
  19. package/plugins/dsh/skills/delphi-review/AGENTS.md +1 -1
  20. package/plugins/dsh/skills/ralph-loop/SKILL.md +1 -1
  21. package/plugins/dsh/skills/ralph-loop/references/components.md +1 -1
  22. package/plugins/dsh/skills/sprint-flow/AGENTS.md +3 -3
  23. package/plugins/dsh/skills/sprint-flow/__tests__/sprint-flow.test.cjs +25 -7
  24. package/plugins/dsh/skills/sprint-flow/references/phase-overview.md +3 -3
  25. package/plugins/dsh/skills/test-specification-alignment/AGENTS.md +1 -1
  26. package/plugins/opencode/package.json +1 -1
  27. package/plugins/opencode/skills/delphi-review/AGENTS.md +1 -1
  28. package/plugins/opencode/skills/ralph-loop/SKILL.md +1 -1
  29. package/plugins/opencode/skills/ralph-loop/references/components.md +1 -1
  30. package/plugins/opencode/skills/sprint-flow/AGENTS.md +3 -3
  31. package/plugins/opencode/skills/sprint-flow/__tests__/sprint-flow.test.cjs +25 -7
  32. package/plugins/opencode/skills/sprint-flow/references/phase-overview.md +3 -3
  33. package/plugins/opencode/skills/test-specification-alignment/AGENTS.md +1 -1
  34. package/plugins/qoder/plugin.json +1 -1
  35. package/plugins/qoder/skills/delphi-review/AGENTS.md +1 -1
  36. package/plugins/qoder/skills/ralph-loop/SKILL.md +1 -1
  37. package/plugins/qoder/skills/ralph-loop/references/components.md +1 -1
  38. package/plugins/qoder/skills/sprint-flow/AGENTS.md +3 -3
  39. package/plugins/qoder/skills/sprint-flow/__tests__/sprint-flow.test.cjs +25 -7
  40. package/plugins/qoder/skills/sprint-flow/references/phase-overview.md +3 -3
  41. package/plugins/qoder/skills/test-specification-alignment/AGENTS.md +1 -1
  42. package/principles/AGENTS.md +103 -97
  43. package/skills/delphi-review/AGENTS.md +1 -1
  44. package/skills/ralph-loop/SKILL.md +1 -1
  45. package/skills/ralph-loop/references/components.md +1 -1
  46. package/skills/sprint-flow/AGENTS.md +3 -3
  47. package/skills/sprint-flow/references/phase-overview.md +3 -3
  48. package/skills/test-specification-alignment/AGENTS.md +1 -1
package/adapters/shell.sh CHANGED
@@ -155,6 +155,49 @@ _shell_test_files() {
155
155
  -not -path './dist/*' 2>/dev/null | sort
156
156
  }
157
157
 
158
+ # Resolve the bats binary the same way typescript.sh resolves its tools.
159
+ #
160
+ # The previous implementation asked `command -v bats` and nothing else. bats is a
161
+ # devDependency, so a real install puts it at node_modules/.bin/bats -- which is
162
+ # NOT on PATH when a git hook runs (git does not source the shell profile, and
163
+ # npm only adds node_modules/.bin for `npm run` scripts). The probe therefore
164
+ # failed on every real commit, the adapter printed "bats not available", returned
165
+ # 0, and Gate 5 recorded a PASS for a suite that was installed and never ran.
166
+ #
167
+ # Measured on this repo: `command -v bats` was empty while
168
+ # node_modules/.bin/bats existed and was executable. The existing
169
+ # adapter-shell-tests.test.bats could not see this because every case prepends a
170
+ # fake bats directory to PATH -- it tested a condition that does not hold in
171
+ # production.
172
+ #
173
+ # Search order mirrors typescript.sh `_local_bin`: the project's own
174
+ # node_modules/.bin first, then a bounded walk up through ancestors because npm
175
+ # hoists to the workspace root. Then, and only then, PATH -- so a globally
176
+ # installed bats still works and explicitly breaking the local one cannot silently
177
+ # resolve to something else. Nothing outside the checkout is required.
178
+ _shell_resolve_bats() {
179
+ local dir depth=0
180
+ if [ -x "node_modules/.bin/bats" ]; then
181
+ printf '%s\n' "node_modules/.bin/bats"
182
+ return 0
183
+ fi
184
+ dir="$(pwd)"
185
+ while [ "$depth" -lt 6 ]; do
186
+ depth=$((depth + 1))
187
+ [ "$dir" = "/" ] && break
188
+ dir="$(dirname "$dir")"
189
+ if [ -x "$dir/node_modules/.bin/bats" ]; then
190
+ printf '%s\n' "$dir/node_modules/.bin/bats"
191
+ return 0
192
+ fi
193
+ done
194
+ if command -v bats >/dev/null 2>&1; then
195
+ command -v bats
196
+ return 0
197
+ fi
198
+ return 1
199
+ }
200
+
158
201
  run_tests() {
159
202
  local suites
160
203
  suites="$(_shell_test_files)"
@@ -166,7 +209,8 @@ run_tests() {
166
209
  return 0
167
210
  fi
168
211
 
169
- if ! command -v bats >/dev/null 2>&1; then
212
+ local bats_bin
213
+ if ! bats_bin="$(_shell_resolve_bats)"; then
170
214
  echo "bats not available, skipping shell test suite (install: npm i -D bats)"
171
215
  return 0
172
216
  fi
@@ -175,8 +219,16 @@ run_tests() {
175
219
  count="$(printf '%s\n' "$suites" | wc -l | tr -d ' ')"
176
220
  echo "Running Shell tests (${count} .bats suite(s))..."
177
221
 
222
+ # Report where bats came from: a locally resolved binary is the common case and
223
+ # making it visible is what turns "the gate ran the suite" into something a
224
+ # reader can verify rather than assume.
225
+ case "$bats_bin" in
226
+ /*) ;;
227
+ *) echo " using ${bats_bin}" ;;
228
+ esac
229
+
178
230
  # shellcheck disable=SC2086 # word-splitting is the point: one arg per suite
179
- bats $suites
231
+ "$bats_bin" $suites
180
232
  return $?
181
233
  }
182
234
 
@@ -186,3 +238,36 @@ run_coverage() {
186
238
  echo "Shell coverage not available"
187
239
  return 0
188
240
  }
241
+
242
+ # Declare that this language's test suite is executed elsewhere (CI), so the
243
+ # commit-time gate must not run it.
244
+ #
245
+ # This is a capability DECLARATION in the #794 sense, not a language-name check
246
+ # in the gate: the adapter is the component that knows its own toolchain, and a
247
+ # list of names can only ever cover the languages someone remembered.
248
+ #
249
+ # Why it is needed at all: `run_tests` has no selection. `_shell_test_files`
250
+ # discovers every *.bats in the repo -- 284 here, measured -- and bats runs all of
251
+ # them. That was invisible because the old `command -v bats` probe failed on every
252
+ # real hook run and returned 0 before reaching the run; once the probe was fixed
253
+ # (see `_shell_resolve_bats`), a commit touching only shell.sh sat with no output
254
+ # for 100s+ and had to be killed, while the same hook on an empty index finished
255
+ # in well under 100s.
256
+ #
257
+ # The suites do still run: CI's `bats-contracts` job, sharded across runners.
258
+ # quality-gates.yml is explicit about not wanting a second copy in the local hook
259
+ # ("do not re-add a silent copy here"), because running them serially measured
260
+ # 18m47s of a 22m24s job. So the gate reports the delegation rather than silently
261
+ # dropping the check -- "not checked here" must stay distinguishable from
262
+ # "checked and clean", and the reader is told where it IS checked.
263
+ #
264
+ # Direct callers are unaffected: this only tells the gate whether to call
265
+ # `run_tests`; it does not disable the function.
266
+ tests_delegated_to_ci() {
267
+ return 0
268
+ }
269
+
270
+ # Where the delegation goes, so the gate can name it instead of saying "skipped".
271
+ tests_delegated_to_ci_target() {
272
+ echo "CI bats-contracts job (scripts/run-bats-ci.cjs)"
273
+ }
@@ -411,7 +411,51 @@ sync-version left a drifted checkout under a green Gate 0.
411
411
  # Build tooling is source for `has_source` (it is code) but not for
412
412
  # `has_real_source` (it needs no VERSION bump) -- so `continue` here
413
413
  # skips only the second flag, keeping the single extension list below.
414
- src/npm-package/adapters/*|src/npm-package/scripts/*|src/npm-package/hooks/*|scripts/*|githooks/adapters/*)
414
+ #
415
+ # #806 G0a: `githooks/gate-entries/*` was missing. Gate bodies live there
416
+ # and are the same kind of code as `githooks/adapters/*` -- both change
417
+ # what the gates DO, neither changes the shipped package's behaviour -- so
418
+ # leaving it out meant an adapter edit passed while a gate-logic edit
419
+ # demanded a VERSION bump. The only ways through were a real bump (which
420
+ # pollutes the version history with changes users cannot observe) or
421
+ # SKIP_VERSION_CHECK=1 (which bypasses the gate instead of satisfying it);
422
+ # the second was used repeatedly, which is how the asymmetry was found.
423
+ #
424
+ # A path prefix exempts everything beneath it, so these tests pin the
425
+ # boundary from both sides: gate-entries passes, and real source under
426
+ # other paths (including a `.sh` outside these prefixes) still blocks.
427
+ #
428
+ # #806 G0b: a skill's `scripts/` and `__tests__/` are the machinery that
429
+ # produces confidence in the skill -- changing them changes no behaviour a
430
+ # user experiences, exactly like the directories above.
431
+ #
432
+ # Deliberately NOT `skills/*`: sync-package-content.js:79 copies the whole
433
+ # of skills/ into the published package, and SKILL.md plus references/ ARE
434
+ # what the agent follows after install. Exempting the whole tree would let
435
+ # a change to shipped behaviour land without appearing anywhere in version
436
+ # history. Exempt the mechanics, not the instructions -- so these patterns
437
+ # anchor on the scripts/ and __tests__/ segments, never on `skills/*`.
438
+ src/npm-package/adapters/*|src/npm-package/scripts/*|src/npm-package/hooks/*|scripts/*|githooks/adapters/*|githooks/gate-entries/*|skills/*/scripts/*|skills/*/__tests__/*)
439
+ has_source=true
440
+ continue
441
+ ;;
442
+ # #806 G0c: test files, anywhere. 684 are tracked across src/, githooks/,
443
+ # scripts/, plugins/ and skills/, and npm ships 261 of them -- the `files`
444
+ # list names directories such as `lib/` and `hooks/`, and the prefix drags
445
+ # their `__tests__/` along. So a test IS in the package, the same argument
446
+ # that exempted a skill's scripts/ and __tests__/ above.
447
+ #
448
+ # What a test asserts is not what a user experiences, and a version number
449
+ # promises a behaviour change. Requiring a bump for test edits trains
450
+ # maintainers to either inflate the version history or reach for
451
+ # SKIP_VERSION_CHECK=1 -- both were observed.
452
+ #
453
+ # Two conventions must both match, because this repo uses both: a
454
+ # `__tests__/` directory (src/, githooks/) and a sibling `*.test.*` file
455
+ # (scripts/, skills/). Anchored on full segments and the dotted infix, not
456
+ # a `*test*` substring -- `contest.cjs` and `latest.cjs` are real modules
457
+ # and stay gated (pinned by name in the tests).
458
+ */__tests__/*|*.test.*)
415
459
  has_source=true
416
460
  continue
417
461
  ;;
@@ -468,8 +512,9 @@ Before committing:
468
512
  2. Add entry to CHANGELOG.md
469
513
  3. Run: node scripts/sync-version.cjs
470
514
 
471
- Build-tooling-only changes (adapters/, scripts/, hooks/) need NO version bump
472
- and pass this gate automatically — no marker required.
515
+ Build-tooling-only changes (adapters/, gate-entries/, scripts/, hooks/, and a
516
+ skill's scripts/ or __tests__/) need NO version bump and pass this gate
517
+ automatically — no marker required.
473
518
 
474
519
  If you genuinely must land production source without a version bump, the
475
520
  supported escape hatch is the env var (a message prefix cannot work here
@@ -29,17 +29,36 @@
29
29
  gate_12_run() {
30
30
  if ! gate_enabled 12; then
31
31
  echo "⏭️ SKIPPED - Gate 12: File hygiene (not selected by XP_GATE_ONLY_GATE)"
32
+ # No GATE_12_DETAIL here (removed with #806 G12a): pre-commit's blocking-exit
33
+ # journal reads GATE_<id>_DETAIL, but only on a blocking exit, and Gate 12 is
34
+ # non-blocking -- so a detail variable for this gate is write-only. Gate 0/1
35
+ # populate one legitimately because they CAN block.
32
36
  GATE_12_STATUS="SKIP"
33
- GATE_12_DETAIL="not_selected"
34
37
  return 0
35
38
  fi
36
39
 
37
40
  if [ -f "$GATE_DIR/gate-12-file-hygiene.sh" ]; then
38
41
  source "$GATE_DIR/gate-12-file-hygiene.sh"
39
42
  elif [ -f "$(git rev-parse --show-toplevel 2>/dev/null)/githooks/gate-12-file-hygiene.sh" ]; then
43
+ # shellcheck source=/dev/null
44
+ # Above: the path is only known at runtime (git rev-parse), so shellcheck
45
+ # cannot follow it and reports SC1090/SC1091. The guard on the preceding
46
+ # `elif` already proves the file exists, so this is a static-analysis
47
+ # limitation, not an unchecked source.
40
48
  source "$(git rev-parse --show-toplevel)/githooks/gate-12-file-hygiene.sh"
41
49
  else
50
+ # #806 G12a: this arm printed SKIPPED and stopped there, so GATE_12_STATUS kept
51
+ # whatever the driver left in it -- measured PASS -- and record_gate_audit was
52
+ # never called, meaning the gate left NO journal line at all. A gate that wrote
53
+ # nothing is indistinguishable from a gate the chain never contained, and the
54
+ # operator was told "SKIPPED" while the machine recorded a pass.
55
+ #
56
+ # Same family as #806 G1a (Gate 1's four SKIP sites) and #806 D2 (Gate 0's
57
+ # --skip-version-check arm): the words said SKIP, the state said PASS.
42
58
  echo "⏭️ SKIPPED - Gate 12: File Hygiene (gate-12-file-hygiene.sh not found)"
59
+ GATE_12_STATUS="SKIP"
60
+ GATE_12_START=$(gate_start_ms)
61
+ record_gate_audit "gate-12" "file-hygiene" "$GATE_12_STATUS" "0" "$GATE_12_START"
43
62
  fi
44
63
  # ============================================================================
45
64
  return 0
@@ -626,6 +626,16 @@ else
626
626
  # Route to appropriate test runner via adapter
627
627
  for CURRENT_LANG in $PROJECT_LANGS; do
628
628
  ADAPTER_FILE=$(resolve_adapter_path "$CURRENT_LANG")
629
+ # Drop declarations left behind by the PREVIOUS adapter before sourcing this
630
+ # one. Adapters are sourced into one shell, so a function one adapter defines
631
+ # stays callable while the next language is being handled -- measured: after
632
+ # shell.sh declared its delegation, powershell was reported as delegating too,
633
+ # even though powershell.sh declares nothing. The consequence is not cosmetic:
634
+ # a stale "yes" removes test verification for a language that never asked for
635
+ # it, which is the exact failure mode the declaration's default is meant to
636
+ # prevent. `unset -f` on an absent function is a no-op, so this is safe for
637
+ # adapters that declare nothing.
638
+ unset -f tests_delegated_to_ci tests_delegated_to_ci_target coverage_runs_tests 2>/dev/null || true
629
639
  if [ "${CURRENT_LANG}" != "unknown" ] && [ -n "$ADAPTER_FILE" ]; then
630
640
  if source "$ADAPTER_FILE" 2>/dev/null; then
631
641
  # TypeScript: vitest with smart test selection
@@ -819,7 +829,28 @@ else
819
829
  # declare it runs the tests here as well. Double-running costs time; not
820
830
  # running them would cost verification, and #794's precedent is that the
821
831
  # slower mistake is the acceptable one for an undeclared adapter.
822
- if adapter_declares_coverage_runs_tests; then
832
+ # An adapter may declare that its suite runs elsewhere. Checked FIRST,
833
+ # because for such an adapter the question below ("does coverage also run
834
+ # the tests?") is moot -- neither branch may call run_tests.
835
+ #
836
+ # Why this exists for shell specifically: `run_tests` has no selection and
837
+ # discovers every *.bats in the repo (284, measured), so calling it here is
838
+ # a multi-hour commit. That was masked by a failing `command -v bats`
839
+ # probe that returned 0 before the run; once the probe was fixed, a
840
+ # shell.sh-only commit hung with no output for 100s+ and had to be killed.
841
+ #
842
+ # The report line is required, not decorative: removing the run must not
843
+ # make the check indistinguishable from one that passed, and the reader
844
+ # has to be told where it IS verified (CI's sharded bats-contracts job,
845
+ # per quality-gates.yml -- "do not re-add a silent copy here").
846
+ if adapter_delegates_tests_to_ci; then
847
+ local _delegated_to
848
+ _delegated_to="$(adapter_test_delegation_target)"
849
+ echo "ℹ️ ${CURRENT_LANG}: tests run in ${_delegated_to}, not at commit time."
850
+ echo " Not checked by this gate -- verified on push/PR instead."
851
+ GATE_5_DETAIL="${GATE_5_DETAIL:+${GATE_5_DETAIL}; }${CURRENT_LANG}: tests delegated to ${_delegated_to}"
852
+ DELEGATED_LANGS="${DELEGATED_LANGS:+${DELEGATED_LANGS} }${CURRENT_LANG}"
853
+ elif adapter_declares_coverage_runs_tests; then
823
854
  echo "ℹ️ ${CURRENT_LANG}: coverage run includes the tests — deferring test execution to a single pass."
824
855
  TESTS_DEFERRED=true
825
856
  else
@@ -1520,7 +1551,30 @@ else
1520
1551
  ;;
1521
1552
  "powershell")
1522
1553
  COVERAGE_ENFORCED=true
1523
- if [ -f "coverage.xml" ]; then
1554
+ # #806 G5a: a repo with no Pester tests can never produce coverage.xml, yet
1555
+ # the branch below demanded one and BLOCKED -- refusing every commit that
1556
+ # touched a .ps1 on evidence the repo could not supply. The gate even printed
1557
+ # "No Pester tests found" earlier in the same run, then blocked for the
1558
+ # missing artifact anyway.
1559
+ #
1560
+ # "There are no tests to run" and "tests ran but coverage is missing" are
1561
+ # different states and must not collapse into one verdict. The first is SKIP
1562
+ # with a reason; the second stays fail-closed (#570: an unavailable
1563
+ # measurement is not a pass). Detection uses the same *.Tests.ps1 convention
1564
+ # the rest of Gate 5 uses, so a repo that acquires tests automatically gets
1565
+ # enforcement back -- there is nothing to remember to flip.
1566
+ if ! find . \( -name '*.Tests.ps1' -o -name '*.Tests.psm1' \) \
1567
+ -not -path './node_modules/*' -not -path './.git/*' \
1568
+ -print -quit 2>/dev/null | grep -q .; then
1569
+ echo "⏭️ SKIPPED - PowerShell coverage: no Pester tests in this project (*.Tests.ps1)"
1570
+ echo " Nothing can produce coverage.xml here, so the floor is not applicable."
1571
+ echo " This is NOT a pass: add Pester tests and coverage is enforced again."
1572
+ if [ -n "$(printf '%s' "${GATE_5_STATUS:-}")" ] && [ "$GATE_5_STATUS" = "PASS" ]; then
1573
+ GATE_5_STATUS="SKIP"
1574
+ fi
1575
+ GATE_5_DETAIL="powershell: no Pester tests (coverage not applicable)"
1576
+ COVERAGE_ENFORCED=false
1577
+ elif [ -f "coverage.xml" ]; then
1524
1578
  # The threshold is passed INTO node: the verdict used to be computed
1525
1579
  # against a hard-coded 80 inside the script, so a project that configured
1526
1580
  # a different floor got a verdict about a number it never set (#570).
package/hooks/pre-commit CHANGED
@@ -370,6 +370,46 @@ adapter_declares_coverage_runs_tests() {
370
370
  ( coverage_runs_tests ) >/dev/null 2>&1
371
371
  }
372
372
 
373
+ # Ask the adapter whether its test suite is executed somewhere else (CI), so the
374
+ # commit-time gate must not run it.
375
+ #
376
+ # Same shape and same reasoning as `adapter_declares_coverage_runs_tests` above,
377
+ # and the asymmetry is again the whole design: a wrong "yes" removes test
378
+ # verification from the commit, so the default for an undeclared adapter is to
379
+ # RUN the tests. The reason the shell adapter declares it is measurable, not
380
+ # stylistic -- its `run_tests` has no selection and discovers every *.bats in the
381
+ # repo (284 here), which is a multi-hour job at commit time.
382
+ #
383
+ # What the declaration must NOT do is make the skip silent. Callers report where
384
+ # the suite actually runs; see gate-5's delegation branch.
385
+ adapter_delegates_tests_to_ci() {
386
+ local scope="${1:-}"
387
+ if [ -n "$scope" ]; then
388
+ (
389
+ # shellcheck disable=SC2086 # $scope is a single command name, deliberately unquoted for eval-free invocation
390
+ $scope >/dev/null 2>&1 || exit 1
391
+ command -v tests_delegated_to_ci >/dev/null 2>&1 || exit 1
392
+ tests_delegated_to_ci >/dev/null 2>&1
393
+ )
394
+ return $?
395
+ fi
396
+ command -v tests_delegated_to_ci >/dev/null 2>&1 || return 1
397
+ ( tests_delegated_to_ci ) >/dev/null 2>&1
398
+ }
399
+
400
+ # Where a delegating adapter's suite runs, for the report line.
401
+ adapter_test_delegation_target() {
402
+ if command -v tests_delegated_to_ci_target >/dev/null 2>&1; then
403
+ local target
404
+ target="$( tests_delegated_to_ci_target 2>/dev/null )"
405
+ if [ -n "$target" ]; then
406
+ printf '%s\n' "$target"
407
+ return 0
408
+ fi
409
+ fi
410
+ printf '%s\n' "CI"
411
+ }
412
+
373
413
  # Gate scripts directory — falls back to project githooks if ADAPTER_DIR doesn't have them.
374
414
  # #505: the probe file and the tier order come from the generated data file, so
375
415
  # this cascade cannot drift from what doctor.js reports.
@@ -2,6 +2,6 @@
2
2
  "verdict": "PASS",
3
3
  "license_type": "MIT",
4
4
  "sha256": "0e7ac423bf2c6e223b7c5b156f8cf72da49d748e56a1641402c31f22ad07dbb5",
5
- "checked_at": "2026-11-16T16:53:30.626Z",
5
+ "checked_at": "2026-11-18T02:40:10.620Z",
6
6
  "source": "network"
7
7
  }
@@ -1,94 +1,96 @@
1
1
  # SRC/MOCK-POLICY KNOWLEDGE BASE
2
2
 
3
- **Generated:** 2026-11-04
4
- **Commit:** eb2097b0
5
- **Branch:** sprint/2026-11-03-02
6
- **Version:** 0.38.8.0
3
+ Mock layering for pre-push Gate M3: internal dependencies get real
4
+ implementations, external ones get mocks, and every pending dependency carries a
5
+ removal plan.
7
6
 
8
- ## OVERVIEW
9
- Mock layering policy enforcement — Gate M3 of pre-push hook. Ensures integration tests use real implementations for internal dependencies, mock external dependencies, and annotate pending mocks with removal plans. Combines project scope scanning, mock decision engine, and per-file validation into a single pipeline.
7
+ ## WHY THIS GATE EXISTS
10
8
 
11
- ## STRUCTURE
12
- ```
13
- src/mock-policy/
14
- ├── types.ts # Type definitions (MockStrategy, ProjectScope, MockDecision, etc.)
15
- ├── schema.ts # Zod schema for MockPolicyConfig validation
16
- ├── config.ts # loadMockPolicyConfig — loads from .mockpolicyrc / .xp-gate/mock-policy.yaml
17
- ├── scope-scanner.ts # scanProjectScope — classifies imports as internal/external/pending
18
- ├── mock-decision-engine.ts # MockDecisionEngine — decides mock vs real per import + test layer
19
- ├── gate-m3.ts # runGateM3 — orchestrator: filter test files → scan scope → validate
20
- └── __tests__/
21
- ├── config.test.ts # Config loader unit tests
22
- ├── scope-scanner.test.ts # Scope scanner unit + tmpdir integration tests
23
- ├── mock-decision-engine.test.ts # Decision engine unit tests
24
- └── integration.test.ts # Full pipeline integration test
25
- ```
9
+ A test that mocks the very thing it is testing always passes. That is not a weak
10
+ test — it is a test that reports success while measuring nothing, and the
11
+ failure surfaces as an incident rather than a red build. Gate M3's whole job is
12
+ to make the difference between "asserted against the real implementation" and
13
+ "asserted against my own stub" visible, because a reviewer cannot reliably tell
14
+ those apart by reading an import line.
15
+
16
+ The policy is expressed as a **decision matrix keyed by test layer**, not a list
17
+ of banned calls. The layer is what makes a mock acceptable: mocking an external
18
+ service in an integration test is correct; mocking the module under test never
19
+ is, and no amount of annotation changes that.
20
+
21
+ ## THE INVARIANTS THAT MATTER
22
+
23
+ **Test layer decides the rule.** e2e = always real. unit (lenient) = always mock
24
+ allowed, unchecked. unit (strict) = treated as integration-like. integration =
25
+ decided by dependency scope. Layer detection is delegated to
26
+ `src/mutation/detect-ai-test.ts` — deliberately not reimplemented here, so the
27
+ two gates cannot disagree about what a file is.
28
+
29
+ **Scope decides mock vs real for integration tests.** An import is internal
30
+ (resolves inside the project boundary) → must be real. External (Node builtin,
31
+ npm package outside the boundary) → mock allowed. Pending (declared but not yet
32
+ implemented) → mock allowed only with a removal plan.
33
+
34
+ **`@mock-justified` is the escape hatch for pending dependencies in integration
35
+ tests, and it demands a removal plan.** Not a suppression: a pending dependency
36
+ without one is exactly the "mock forever" state the gate exists to prevent.
37
+
38
+ **Default severity is `warning` — Gate M3 does not block a push.** This is
39
+ intentional while the matrix is being adopted; it means a green push is not
40
+ evidence that mock layering is satisfied. Read the gate's output, do not rely on
41
+ the exit status.
42
+
43
+ **Config resolves `.mockpolicyrc` (JSON) > `.xp-gate/mock-policy.yaml` (YAML) >
44
+ built-in defaults**, and is Zod-validated before use. A malformed config fails
45
+ rather than silently falling back to defaults — a gate graded against a config
46
+ nobody wrote is worse than a gate that refuses to run.
47
+
48
+ ## TRAPS
49
+
50
+ **`gate-m3.ts`'s helpers are deliberately not exported** (beyond
51
+ `runGateM`/`main`). Importing them couples callers to internals the matrix is
52
+ free to change; go through `runGateM`.
53
+
54
+ **The scanner touches the real filesystem.** There is no virtual-FS abstraction,
55
+ so scope resolution reflects the working tree — a file that exists only in the
56
+ index, or a path that requires a build step to exist, classifies as
57
+ unimplemented. Tests account for this by building real temp directories under
58
+ `os.tmpdir()`.
59
+
60
+ **`workspace:*` dependencies are skipped** when reading `package.json`, because
61
+ they are neither versioned releases nor external services.
62
+
63
+ **Do not set severity to `error` without running the full integration suite
64
+ first.** The matrix's default is `warning` precisely because the codebase's
65
+ current mock usage has not been validated against a blocking threshold.
26
66
 
27
67
  ## WHERE TO LOOK
28
- | Task | Location | Notes |
29
- |------|----------|-------|
30
- | Types/Interfaces | types.ts | MockStrategy, ProjectScope, MockPolicyConfig, MockPolicyResult |
31
- | Config loading | config.ts | .mockpolicyrc (JSON) > .xp-gate/mock-policy.yaml (YAML) > DEFAULT_CONFIG |
32
- | Schema validation | schema.ts | Zod schema for full config validation |
33
- | Scope scanning | scope-scanner.ts | scanProjectScope, classifyDependency, isExternalImport, loadExternalDependencies |
34
- | Mock decisions | mock-decision-engine.ts | MockDecisionEngine.decide() — decision matrix per test layer |
35
- | Gate runner | gate-m3.ts | runGateM3, validateFile, collectImports, detectMockUsage |
36
- | Integration tests | __tests__/integration.test.ts | End-to-end pipeline with temp project directories |
37
-
38
- ## CODE MAP
39
- | Symbol | Type | Location | Role |
40
- |--------|------|----------|------|
41
- | runGateM3 | Function | gate-m3.ts | Orchestrator: filter test files → scan scope → validate → return MockPolicyResult |
42
- | validateFile | Function | gate-m3.ts | Per-file validation: read content → detect layer → check imports → compare decision vs usage |
43
- | collectImports | Function | gate-m3.ts | Regex-based import extraction (static + dynamic) |
44
- | detectMockUsage | Function | gate-m3.ts | Checks for vi.mock/jest.mock/vi.doMock calls matching an import |
45
- | MockDecisionEngine | Class | mock-decision-engine.ts | decide(importPath, layer) → MockDecision with strategy/reason/pendingRemoval |
46
- | scanProjectScope | Function | scope-scanner.ts | Classifies imports into implemented/unimplemented/external |
47
- | classifyDependency | Function | scope-scanner.ts | Single dependency scope classification with optional existCache |
48
- | isExternalImport | Function | scope-scanner.ts | Checks Node.js builtins, bare npm packages, boundary patterns |
49
- | loadExternalDependencies | Function | scope-scanner.ts | Reads package.json dependencies (skips workspace:* protocol) |
50
- | loadMockPolicyConfig | Function | config.ts | Config loader with fallback chain and Zod validation |
51
- | detectTestLayer | Function | src/mutation/detect-ai-test.ts | Classifies test file path as unit/integration/e2e/unknown |
52
-
53
- ## CONVENTIONS
54
- - Decision matrix: e2e=always real, unit(lenient)=always mock, unit(strict)=integration-like, integration=scope-based
55
- - Pending dependencies in integration tests require `@mock-justified` annotation
56
- - Default severity: `warning` (does NOT block push)
57
- - Default boundary: `['src/**']`
58
- - Default integration policy: strict, requireRealForImplemented=true, allowExternalMock=true, requirePendingRemoval=true
59
- - Default e2e policy: strict, allowExternalMock=false, maxMockDensity=0
60
- - Unit tests with lenient policy are not checked — all mocks allowed
61
- - Config resolution: `.mockpolicyrc` (JSON) > `.xp-gate/mock-policy.yaml` (YAML) > `DEFAULT_CONFIG`
62
- - Config validated via Zod schema before use
63
-
64
- ## ANTI-PATTERNS (THIS PROJECT)
65
- - Do NOT use `as any` or `@ts-ignore` in mock-policy code
66
- - Do NOT set severity to `error` without verifying integration test suite
67
- - Do NOT disable mock checks entirely by setting zero thresholds
68
- - Do NOT import from `gate-m3.ts` private functions — they are deliberately not exported
69
-
70
- ## UNIQUE STYLES
71
- - Gate M3 is the third pre-push gate (after Gate M mutation + Gate M2 AI test detection)
72
- - Pipeline: filterTestFiles → loadConfig → collectAllImports → scanProjectScope → MockDecisionEngine → validateFile per file → aggregate violations
73
- - Uses real filesystem for scope scanning (no virtual filesystem abstraction)
74
- - Integration tests use tmpdir with real package.json + source files
75
- - Test layer detection delegates to `src/mutation/detect-ai-test.ts`
76
68
 
77
- ## COMMANDS
78
- ```bash
79
- # Run Gate M3 directly on changed files
80
- npx tsx src/mock-policy/gate-m3.ts <test-file-1> <test-file-2> ...
69
+ | Task | File |
70
+ |---|---|
71
+ | Types / interfaces | `types.ts` |
72
+ | Zod config schema | `schema.ts` |
73
+ | Config loading + fallback chain | `config.ts` |
74
+ | Internal / external / pending classification | `scope-scanner.ts` |
75
+ | Per-layer mock decision matrix | `mock-decision-engine.ts` |
76
+ | Gate orchestration, per-file validation | `gate-m3.ts` |
77
+
78
+ For the exact exported symbol names and signatures, read the files — a list here
79
+ would rot, and the file *is* the answer.
81
80
 
82
- # Run all mock-policy unit tests
83
- npx vitest run src/mock-policy/__tests__/
81
+ ## COMMANDS
84
82
 
85
- # Run just the integration test
86
- npx vitest run src/mock-policy/__tests__/integration.test.ts
83
+ ```bash
84
+ npx tsx src/mock-policy/gate-m3.ts <test-file>... # run Gate M3 on given files
85
+ npx vitest run src/mock-policy/__tests__/ # this module's tests
87
86
  ```
88
87
 
89
- ## NOTES
90
- - Gate M3 is invoked by pre-push hook after Gate M (mutation) and Gate M2 (AI test detection)
91
- - code walkthrough scope: no hard file-count or LOC threshold; large diffs require complete review or user-directed splitting, never a size-based bypass
92
- - Coverage exclude: src/mock-policy/ controlled by vitest config
93
- - The integration test creates real temporary directories under os.tmpdir()
94
- - Dependencies on: `src/mutation/detect-ai-test.ts` (detectTestLayer)
88
+ ## WHEN YOU CHANGE SOMETHING
89
+
90
+ - Adding a test layer → update the matrix in `mock-decision-engine.ts` **and**
91
+ `src/mutation/detect-ai-test.ts`; the two must agree or files classify into a
92
+ layer the matrix has no rule for.
93
+ - Changing severity → run the whole suite first; `warning` became the default
94
+ because blocking was never validated against real usage.
95
+ - Coverage exclusion for this directory is controlled by the vitest config, not
96
+ from here.