@boyingliu01/xp-gate 0.37.3 → 0.38.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 (116) hide show
  1. package/adapter-common.sh +12 -2
  2. package/adapters/csharp.sh +73 -2
  3. package/adapters/dart.sh +13 -0
  4. package/adapters/go.sh +5 -0
  5. package/adapters/iac.sh +46 -3
  6. package/adapters/java.sh +6 -0
  7. package/adapters/kotlin.sh +6 -0
  8. package/adapters/shell.sh +119 -34
  9. package/adapters/swift.sh +6 -0
  10. package/adapters/typescript.sh +98 -34
  11. package/bin/xp-gate.js +48 -2
  12. package/gate-10.sh +99 -26
  13. package/gate-12-file-hygiene.sh +13 -1
  14. package/gate-registry.sh +197 -0
  15. package/gates/python-health.ts +67 -29
  16. package/hooks/adapter-common.sh +12 -2
  17. package/hooks/deploy-manifest.sh +100 -0
  18. package/hooks/gate-10.sh +99 -26
  19. package/hooks/gate-12-file-hygiene.sh +13 -1
  20. package/hooks/gate-driver.sh +120 -0
  21. package/hooks/gate-entries/gate-0-entry.sh +825 -0
  22. package/hooks/gate-entries/gate-1-entry.sh +767 -0
  23. package/hooks/gate-entries/gate-10-entry.sh +52 -0
  24. package/hooks/gate-entries/gate-11-entry.sh +120 -0
  25. package/hooks/gate-entries/gate-12-entry.sh +44 -0
  26. package/hooks/gate-entries/gate-12b-entry.sh +178 -0
  27. package/hooks/gate-entries/gate-12c-entry.sh +80 -0
  28. package/hooks/gate-entries/gate-13-entry.sh +584 -0
  29. package/hooks/gate-entries/gate-2-entry.sh +199 -0
  30. package/hooks/gate-entries/gate-3-entry.sh +53 -0
  31. package/hooks/gate-entries/gate-4-entry.sh +46 -0
  32. package/hooks/gate-entries/gate-5-entry.sh +1729 -0
  33. package/hooks/gate-entries/gate-6-entry.sh +658 -0
  34. package/hooks/gate-entries/gate-7-entry.sh +41 -0
  35. package/hooks/gate-entries/gate-8-entry.sh +33 -0
  36. package/hooks/gate-entries/gate-9-entry.sh +307 -0
  37. package/hooks/gate-entries/subdir-restore.sh +27 -0
  38. package/hooks/gate-registry.sh +51 -15
  39. package/hooks/hook-module-resolution.sh +73 -0
  40. package/hooks/install.sh +135 -0
  41. package/hooks/lib/now-ms.sh +55 -19
  42. package/hooks/lib/toolchain-path.sh +50 -6
  43. package/hooks/pre-commit +256 -5091
  44. package/hooks/pre-push +212 -25
  45. package/lib/__tests__/arch-config-template.test.js +190 -0
  46. package/lib/__tests__/baseline-shell-scope.test.js +60 -0
  47. package/lib/__tests__/crap-cli.test.js +14 -3
  48. package/lib/__tests__/deploy-manifest-check-wired.test.js +138 -0
  49. package/lib/__tests__/deploy-manifest-completeness.test.js +151 -0
  50. package/lib/__tests__/deploy-manifest-consumers-adapter-uninstall.test.js +40 -0
  51. package/lib/__tests__/deploy-manifest-consumers-no-private-lists.test.js +74 -0
  52. package/lib/__tests__/deploy-manifest-projection.test.js +66 -0
  53. package/lib/__tests__/deploy-manifest-shell-parity.test.js +108 -0
  54. package/lib/__tests__/deploy-manifest.test.js +97 -0
  55. package/lib/__tests__/doctor.test.js +51 -7
  56. package/lib/__tests__/gate-coverage.test.js +79 -12
  57. package/lib/__tests__/gate-numbering.test.js +28 -1
  58. package/lib/__tests__/install-sh-deploy-manifest.test.js +80 -0
  59. package/lib/__tests__/mirror-sync.test.js +45 -3
  60. package/lib/__tests__/npm-package.test.js +10 -7
  61. package/lib/__tests__/sastd-client.test.js +514 -0
  62. package/lib/__tests__/shared-utils-copyHooks-manifest.test.js +69 -0
  63. package/lib/__tests__/sprint-status-rework.test.js +1 -0
  64. package/lib/arch-config-template.js +87 -0
  65. package/lib/baseline.js +54 -2
  66. package/lib/deploy-manifest.js +174 -0
  67. package/lib/doctor.js +46 -14
  68. package/lib/gate-capability.js +291 -0
  69. package/lib/gate-coverage.js +194 -74
  70. package/lib/gate-identity.js +349 -0
  71. package/lib/gate-runner.js +11 -1
  72. package/lib/hook-module-resolution.js +27 -0
  73. package/lib/init.js +72 -5
  74. package/lib/mattpocock-license-verdict.json +1 -1
  75. package/lib/sastd-client.js +572 -0
  76. package/lib/shared-utils.js +31 -9
  77. package/lib/uninstall.js +10 -7
  78. package/lib/update-hooks.js +27 -18
  79. package/mock-policy/AGENTS.md +1 -1
  80. package/mutation/AGENTS.md +1 -1
  81. package/package.json +3 -1
  82. package/plugins/claude-code/.claude-plugin/plugin.json +1 -1
  83. package/plugins/claude-code/skills/delphi-review/AGENTS.md +1 -1
  84. package/plugins/claude-code/skills/sprint-flow/AGENTS.md +1 -1
  85. package/plugins/claude-code/skills/test-specification-alignment/AGENTS.md +1 -1
  86. package/plugins/dsh/package.json +1 -1
  87. package/plugins/dsh/skills/delphi-review/AGENTS.md +1 -1
  88. package/plugins/dsh/skills/sprint-flow/AGENTS.md +1 -1
  89. package/plugins/dsh/skills/test-specification-alignment/AGENTS.md +1 -1
  90. package/plugins/opencode/package.json +1 -1
  91. package/plugins/opencode/skills/delphi-review/AGENTS.md +1 -1
  92. package/plugins/opencode/skills/sprint-flow/AGENTS.md +1 -1
  93. package/plugins/opencode/skills/test-specification-alignment/AGENTS.md +1 -1
  94. package/plugins/qoder/plugin.json +1 -1
  95. package/plugins/qoder/skills/delphi-review/AGENTS.md +1 -1
  96. package/plugins/qoder/skills/sprint-flow/AGENTS.md +1 -1
  97. package/plugins/qoder/skills/test-specification-alignment/AGENTS.md +1 -1
  98. package/principles/AGENTS.md +1 -1
  99. package/principles/__tests__/analyzer.test.ts +2 -1
  100. package/principles/__tests__/config-enforcement.test.ts +1 -0
  101. package/principles/__tests__/types.test.ts +1 -0
  102. package/principles/adapters/base.ts +14 -1
  103. package/principles/adapters/duplication.ts +134 -0
  104. package/principles/rules/__tests__/clean-code/large-file.test.ts +2 -1
  105. package/principles/rules/clean-code/code-duplication.ts +75 -9
  106. package/principles/types.ts +39 -0
  107. package/scripts/__tests__/check-mattpocock-license.test.js +36 -3
  108. package/scripts/__tests__/sync-package-content.test.js +12 -2
  109. package/scripts/generate-mirrors.cjs +125 -0
  110. package/scripts/sync-package-content.js +64 -20
  111. package/skills/delphi-review/AGENTS.md +1 -1
  112. package/skills/sprint-flow/AGENTS.md +1 -1
  113. package/skills/test-specification-alignment/AGENTS.md +1 -1
  114. package/adapters/gate-9.sh +0 -245
  115. package/gate-9.sh +0 -245
  116. package/hooks/gate-9.sh +0 -245
package/hooks/pre-push CHANGED
@@ -46,6 +46,28 @@ REMOTE="$1"
46
46
  URL="$2"
47
47
  _PRE_PUSH_REPORT_DONE=0
48
48
 
49
+ # The gate registry answers "what is gate MW called and which file decides it"
50
+ # without reading 1200 lines of this hook. Optional by design: a consumer repo
51
+ # installed from an older package has no registry, and this hook must keep
52
+ # working there -- same contract as pre-commit:318-323.
53
+ #
54
+ # Registering is BOOKKEEPING, not execution policy: the gates below keep their
55
+ # own order and skip semantics. Before this, the registry knew nothing about any
56
+ # pre-push gate, so half the gates this project runs could not be looked up by
57
+ # name at all (#769).
58
+ _PRE_PUSH_GATE_DIR="$(cd "$(dirname "$0")" 2>/dev/null && pwd)"
59
+ _PRE_PUSH_REGISTRY="$_PRE_PUSH_GATE_DIR/gate-registry.sh"
60
+ [ -f "$_PRE_PUSH_REGISTRY" ] || _PRE_PUSH_REGISTRY="$(git rev-parse --show-toplevel 2>/dev/null)/githooks/gate-registry.sh"
61
+ if [ -f "$_PRE_PUSH_REGISTRY" ]; then
62
+ # shellcheck source=/dev/null
63
+ . "$_PRE_PUSH_REGISTRY"
64
+ PRE_PUSH_REGISTRY_STATUS="loaded"
65
+ else
66
+ # Absent is not a failure: record it so a missing registry is visible in the
67
+ # journal instead of silently indistinguishable from "nothing to report".
68
+ PRE_PUSH_REGISTRY_STATUS="missing"
69
+ fi
70
+
49
71
  write_pre_push_report() {
50
72
  local exit_code="$1"
51
73
  local timestamp report_ts reports_dir report_file commit_hash verdict
@@ -59,6 +81,36 @@ write_pre_push_report() {
59
81
  commit_hash=$(git rev-parse HEAD 2>/dev/null) || commit_hash=""
60
82
  commit_hash=$(printf '%s' "$commit_hash" | tr -d '\r\n'); [ -n "$commit_hash" ] || commit_hash="unknown"
61
83
  verdict=$([ "$exit_code" -eq 0 ] && echo "PASS" || echo "BLOCKED")
84
+ # #798: run-level wall-clock duration, from the shared now_ms clock. Emitted as
85
+ # Python `None` when unmeasurable so the field is explicitly JSON null rather
86
+ # than a believable 0 — the same rule pre-commit's duration_ms follows.
87
+ #
88
+ # Lower bound: the push cannot have run for less than the slowest gate it
89
+ # recorded. A value below that means the arithmetic is wrong, and a wrong
90
+ # number here is acted upon; null is the honest answer.
91
+ local xp_push_duration_ms="None"
92
+ if [ -n "${PRE_PUSH_START_MS:-}" ]; then
93
+ local _xp_push_now _xp_push_floor
94
+ _xp_push_now="$(now_ms 2>/dev/null || true)"
95
+ case "$_xp_push_now" in
96
+ ''|*[!0-9]*) _xp_push_now="" ;;
97
+ esac
98
+ _xp_push_floor="${MP_DURATION_MS:-0}"; case "$_xp_push_floor" in ''|*[!0-9]*) _xp_push_floor=0 ;; esac
99
+ if [ -n "${M_DURATION_MS:-}" ]; then
100
+ case "$M_DURATION_MS" in
101
+ ''|*[!0-9]*) : ;;
102
+ *) [ "$M_DURATION_MS" -gt "$_xp_push_floor" ] && _xp_push_floor="$M_DURATION_MS" ;;
103
+ esac
104
+ fi
105
+ if [ -n "$_xp_push_now" ] && [ "$_xp_push_now" -gt "$PRE_PUSH_START_MS" ]; then
106
+ local _xp_push_total=$(( _xp_push_now - PRE_PUSH_START_MS ))
107
+ if [ "$_xp_push_total" -ge "$_xp_push_floor" ]; then
108
+ xp_push_duration_ms="$_xp_push_total"
109
+ else
110
+ echo " ⚠️ pre-push duration_ms rejected: measured ${_xp_push_total}ms is below the slowest gate (${_xp_push_floor}ms) — recording null." >&2
111
+ fi
112
+ fi
113
+ fi
62
114
  mkdir -p "$reports_dir"
63
115
  # #544: the survivor detail is a JSON document, so it cannot be interpolated
64
116
  # into this heredoc — a single quote in a path would break the Python source.
@@ -152,7 +204,7 @@ write_pre_push_report() {
152
204
  printf '%s\n' ' survivors_detail = json.loads(_survivors_raw) if _survivors_raw else None'
153
205
  printf '%s\n' 'except (ValueError, TypeError):'
154
206
  printf '%s\n' ' survivors_detail = None'
155
- printf '%s\n' "_m_details = {'skip_reason': '${GATE_M_SKIP_REASON:-}', 'duration_ms': '${M_DURATION_MS:-0}', 'mutation_score': '${M_SCORE:-}'}"
207
+ printf '%s\n' "_m_details = {'skip_reason': '${GATE_M_SKIP_REASON:-}', 'skip_kind': '${GATE_M_SKIP_KIND:-}', 'duration_ms': '${M_DURATION_MS:-0}', 'mutation_score': '${M_SCORE:-}'}"
156
208
  printf '%s\n' 'if survivors_detail is not None:'
157
209
  printf '%s\n' " _m_details['survivors'] = json.dumps(survivors_detail, sort_keys=True)"
158
210
  printf '%s\n' 'report = {'
@@ -160,6 +212,7 @@ write_pre_push_report() {
160
212
  printf '%s\n' " 'trigger': 'pre-push',"
161
213
  printf '%s\n' " 'branch': '$CURRENT_BRANCH',"
162
214
  printf '%s\n' " 'commit': '$commit_hash',"
215
+ printf '%s\n' " 'duration_ms': $xp_push_duration_ms,"
163
216
  printf '%s\n' " 'changed_files': [f for f in pushed_files if f],"
164
217
  printf '%s\n' " 'overall': {"
165
218
  printf '%s\n' " 'score': None,"
@@ -307,7 +360,7 @@ fi
307
360
 
308
361
  # Determine if pushed files contain ONLY documentation/non-source files
309
362
  DOC_ONLY=true
310
- SOURCE_EXTENSIONS="\.py$|\.js$|\.cjs$|\.mjs$|\.ts$|\.tsx$|\.java$|\.go$|\.rs$|\.cpp$|\.c$|\.swift$|\.kt$|\.sh$|\.dart$|\.ps1$|\.m$|\.mm$|\.h$|\.hpp$"
363
+ SOURCE_EXTENSIONS="\.py$|\.js$|\.cjs$|\.mjs$|\.ts$|\.tsx$|\.java$|\.go$|\.rs$|\.cpp$|\.cc$|\.cxx$|\.c$|\.h$|\.hpp$|\.swift$|\.kt$|\.kts$|\.sh$|\.dart$|\.ps1$|\.psm1$|\.m$|\.mm$|\.cs$|\.csx$|\.fs$|\.fsx$|\.vb$|\.php$|\.rb$|\.lua$|\.pl$"
311
364
 
312
365
  # Extensionless hook scripts and test files are CODE, not documentation.
313
366
  # Measured consequence of the old list: a commit touching githooks/pre-push and
@@ -323,11 +376,21 @@ for file in $PUSHED_FILES; do
323
376
  fi
324
377
  done
325
378
 
326
- # Documentation-only changes (no source code) → skip walkthrough
379
+ # Documentation-only changes (no source code) -> skip walkthrough
380
+ #
381
+ # #798: this branch used to print an affirmative "No code review required.
382
+ # Proceeding with push..." - an AFFIRMATIVE conclusion produced by the very
383
+ # check that just failed to recognise the files as source. A C# project (.cs
384
+ # missing from SOURCE_EXTENSIONS) got that green line on every push, having run
385
+ # zero gates. "Not applicable" and "passed" must not read the same, so the
386
+ # message now states what actually happened and what was NOT checked.
327
387
  if [ "$DOC_ONLY" = "true" ]; then
328
- echo "📚 Documentation-only push (no source code files)."
329
- echo " Files: $(echo "$PUSHED_FILES" | tr '\n' ', ' | sed 's/,$//')"
330
- echo " ✅ No code review required. Proceeding with push..."
388
+ echo "No source code files in this push - pre-push gates NOT applicable."
389
+ echo " Files: $(echo "$PUSHED_FILES" | tr '
390
+ ' ', ' | sed 's/,$//')"
391
+ echo " SKIPPED - code walkthrough and mutation gates did not run."
392
+ echo " If this project has a source language missing from SOURCE_EXTENSIONS,"
393
+ echo " these gates are silently inert. Check the list near the top of this hook."
331
394
  exit 0
332
395
  fi
333
396
 
@@ -342,19 +405,48 @@ fi
342
405
  # guard runs here (fail-closed) and in CI's mirror-parity job. Read-only:
343
406
  # compares bytes and git index modes; heals nothing.
344
407
  GATE_MP_STATUS="SKIP"
345
- # Duration is audited in MILLISECONDS end-to-end (#521 AC-2; the #524 lesson:
346
- # never mix a seconds timestamp into a ms budget). The output is validated as
347
- # bare digits before use: BSD/macOS date does not support %3N and prints the
348
- # literal '...%3N' with exit 0, which would blow up the arithmetic and kill
349
- # pre-push — a non-numeric read degrades to 0 (walkthrough MJ-01).
408
+ # #798: duration is audited in MILLISECONDS end-to-end (#521 AC-2; the #524
409
+ # lesson: never mix a seconds timestamp into a ms budget).
410
+ #
411
+ # The clock is now the SHARED lib/now-ms.sh helper, not a private `date +%s%3N`.
412
+ # That difference mattered: on Windows Git Bash `date +%s%3N` prints the literal
413
+ # "...%3N" and exits 0, so the `|| true` fallback never fired and the value had
414
+ # to be discarded to 0 — every pre-push gate duration read as 0ms. now_ms()
415
+ # prefers node Date.now() and regex-validates its output on every platform.
416
+ #
417
+ # Resolution order mirrors pre-commit: beside the hook, then hooks/lib/ (older
418
+ # installs), then the repo source.
419
+ for _xp_now_ms_candidate in \
420
+ "$(dirname "${BASH_SOURCE[0]}")/lib/now-ms.sh" \
421
+ "$(dirname "${BASH_SOURCE[0]}")/hooks/lib/now-ms.sh" \
422
+ "$(dirname "${BASH_SOURCE[0]}")/../githooks/lib/now-ms.sh"; do
423
+ if [ -f "$_xp_now_ms_candidate" ]; then
424
+ # shellcheck disable=SC1090 # sourcing the resolved lib is the contract here
425
+ source "$_xp_now_ms_candidate"
426
+ break
427
+ fi
428
+ done
429
+ unset _xp_now_ms_candidate
430
+ # Without the helper timing is unmeasurable: emit nothing rather than
431
+ # substituting a different clock, so the report omits the field (#640's rule).
432
+ if ! command -v now_ms >/dev/null 2>&1; then
433
+ now_ms() { printf ''; }
434
+ fi
350
435
  _mp_now_ms() {
351
436
  local _t
352
- _t="$(date +%s%3N 2>/dev/null || true)"
437
+ _t="$(now_ms 2>/dev/null || true)"
353
438
  case "$_t" in
354
439
  ''|*[!0-9]*) echo 0 ;;
355
440
  *) echo "$_t" ;;
356
441
  esac
357
442
  }
443
+ # #798: run-level start, latched before ANY gate. Pre-push reports carried only
444
+ # per-gate timings (M, MP) and no total, so the chain as a whole was never
445
+ # measurable — the issue recorded "pre-push 报告里根本没有耗时字段".
446
+ PRE_PUSH_START_MS="$(now_ms 2>/dev/null || true)"
447
+ case "$PRE_PUSH_START_MS" in
448
+ ''|*[!0-9]*) PRE_PUSH_START_MS="" ;;
449
+ esac
358
450
  MP_START_MS="$(_mp_now_ms)"
359
451
  MP_ROOT=$(git rev-parse --show-toplevel 2>/dev/null) || MP_ROOT=""
360
452
  MP_ROOT=$(printf '%s' "$MP_ROOT" | tr -d '
@@ -531,23 +623,112 @@ echo "━━━━━━━━━━━━━━━━━━━━━━━━
531
623
  echo " GATE M: MUTATION TESTING"
532
624
  echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
533
625
 
534
- # Source adapter-common.sh — 3-tier resolution (global → project → script dir)
535
- ADAPTER_COMMON=""
536
- GLOBAL_ADAPTER_DIR="$HOME/.config/xp-gate/adapters"
626
+ # Source adapter-common.sh through the GENERATED resolution table (REQ-RESOLVE-001).
627
+ #
628
+ # WHAT THIS REPLACED
629
+ # ------------------
630
+ # This block used to be hand-written:
631
+ #
632
+ # if [[ -f "$GLOBAL_ADAPTER_DIR/adapter-common.sh" ]]; then ...
633
+ # elif [[ -f "$PROJECT_GITHOOKS/adapter-common.sh" ]]; then ...
634
+ # elif [[ -f "$(dirname "$0")/adapter-common.sh" ]]; then ...
635
+ #
636
+ # Three lines that looked obviously correct and were inverted. The generated
637
+ # data (`ADAPTER_DIR_ORDER`, in hook-module-resolution.js) declares PROJECT
638
+ # first, on purpose: the global install is a machine-wide DEFAULT that a repo's
639
+ # own githooks/ must be able to override. The hand-written cascade tried GLOBAL
640
+ # first, so on any machine with a global install, every per-project githooks/
641
+ # was unreachable — including this repository's, whose own gate scripts
642
+ # therefore never ran while the log said they had (#495 AC-495-23).
643
+ #
644
+ # The order is not restated here. `_hook_tier_dir` comes from the generated file,
645
+ # so there is no second implementation left to drift. If somebody adds a fourth
646
+ # tier to ADAPTER_DIR_ORDER, this hook picks it up with no edit.
647
+ SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
537
648
  PROJECT_GITHOOKS="$(git rev-parse --show-toplevel 2>/dev/null)/githooks"
649
+ GLOBAL_ADAPTER_DIR="$HOME/.config/xp-gate/adapters"
538
650
 
539
- if [[ -f "$GLOBAL_ADAPTER_DIR/adapter-common.sh" ]]; then
540
- ADAPTER_COMMON="$GLOBAL_ADAPTER_DIR/adapter-common.sh"
541
- elif [[ -f "$PROJECT_GITHOOKS/adapter-common.sh" ]]; then
542
- ADAPTER_COMMON="$PROJECT_GITHOOKS/adapter-common.sh"
543
- elif [[ -f "$(dirname "$0")/adapter-common.sh" ]]; then
544
- ADAPTER_COMMON="$(dirname "$0")/adapter-common.sh"
651
+ ADAPTER_COMMON=""
652
+ GATE_M_SKIP_KIND=""
653
+
654
+ # Locate the generated table next to this hook. It ships in HOOK_FILES, so it is
655
+ # present wherever the hooks are installed; a missing copy is a real install
656
+ # defect and must be reported, never papered over by falling back to a private
657
+ # copy of the order.
658
+ HOOK_RESOLUTION_FILE="$SCRIPT_DIR/hook-module-resolution.sh"
659
+
660
+ if [ ! -f "$HOOK_RESOLUTION_FILE" ]; then
661
+ echo "⚠️ hook-module-resolution.sh not found at $HOOK_RESOLUTION_FILE"
662
+ echo " Run: xp-gate init (or reinstall the hooks)"
663
+ echo "⚠️ Could not resolve adapter-common.sh. SKIP — Gate M."
664
+ GATE_M_SKIP_REASON="hook-module-resolution.sh not found: $HOOK_RESOLUTION_FILE"
665
+ GATE_M_SKIP_KIND="missing"
666
+ # shellcheck source=githooks/hook-module-resolution.sh
667
+ elif ! source "$HOOK_RESOLUTION_FILE" 2>/dev/null; then
668
+ echo "⚠️ hook-module-resolution.sh is corrupt: $HOOK_RESOLUTION_FILE"
669
+ echo " Run: node scripts/generate-hook-resolution.cjs (or reinstall)"
670
+ echo "⚠️ Could not source hook-module-resolution.sh. SKIP — Gate M."
671
+ GATE_M_SKIP_REASON="hook-module-resolution.sh failed to source: $HOOK_RESOLUTION_FILE"
672
+ GATE_M_SKIP_KIND="corrupt"
673
+ elif ! declare -F _hook_tier_dir >/dev/null 2>&1; then
674
+ # Schema < 2: the file parses and sources cleanly but predates the resolver.
675
+ # A file that installs without error and provides nothing is the worst case —
676
+ # it looks like a successful install.
677
+ echo "⚠️ hook-module-resolution.sh is STALE (schema ${HOOK_RESOLUTION_SCHEMA:-1}, need 2)."
678
+ echo " Run: xp-gate update-hooks (regenerates the resolution table)"
679
+ echo "⚠️ Could not resolve adapter-common.sh. SKIP — Gate M."
680
+ GATE_M_SKIP_REASON="hook-module-resolution.sh is stale: schema ${HOOK_RESOLUTION_SCHEMA:-1}, need 2"
681
+ GATE_M_SKIP_KIND="stale"
682
+ elif [ -n "$_HOOK_RESOLVE_BROKEN" ]; then
683
+ # case D: valid syntax, function present, contract wrong. Caught at load time
684
+ # by the generated selfcheck instead of blowing up mid-push at a random call.
685
+ echo "⚠️ hook-module-resolution.sh contract selfcheck failed: $_HOOK_RESOLVE_BROKEN"
686
+ echo " Run: xp-gate update-hooks"
687
+ echo "⚠️ Could not resolve adapter-common.sh. SKIP — Gate M."
688
+ GATE_M_SKIP_REASON="hook-module-resolution.sh contract mismatch: $_HOOK_RESOLVE_BROKEN"
689
+ GATE_M_SKIP_KIND="contract_mismatch"
690
+ else
691
+ # Walk the declared tiers IN ORDER and take the first one whose probe exists.
692
+ # The order comes from HOOK_ADAPTER_DIR_TIERS; this loop does not know which
693
+ # tier "should" win, which is the point.
694
+ for _tier in "${HOOK_ADAPTER_DIR_TIERS[@]}"; do
695
+ _tier_id="${_tier%%|*}"
696
+ _tier_rest="${_tier#*|}"
697
+ _tier_base="${_tier_rest%%|*}"
698
+ _tier_probe="${_tier_rest#*|}"
699
+ _tier_dir="$(_hook_tier_dir "$_tier_id" "$_tier_base")"
700
+ [ -n "$_tier_dir" ] || continue
701
+ if [ -f "$_tier_dir/$_tier_probe" ]; then
702
+ ADAPTER_COMMON="$_tier_dir/$_tier_probe"
703
+ break
704
+ fi
705
+ done
545
706
  fi
546
- # shellcheck source=githooks/adapter-common.sh
547
- source "$ADAPTER_COMMON" 2>/dev/null || {
707
+
708
+ if [ -n "$ADAPTER_COMMON" ]; then
709
+ # shellcheck source=githooks/adapter-common.sh
710
+ if ! source "$ADAPTER_COMMON" 2>/dev/null; then
711
+ echo "⚠️ Could not source adapter-common.sh from $ADAPTER_COMMON. SKIP — Gate M."
712
+ GATE_M_SKIP_REASON="adapter-common.sh could not be sourced: $ADAPTER_COMMON"
713
+ GATE_M_SKIP_KIND="source_failed"
714
+ ADAPTER_COMMON=""
715
+ fi
716
+ elif [ -z "$GATE_M_SKIP_KIND" ]; then
717
+ # No tier held adapter-common.sh. Report every tier that was tried, so the
718
+ # message says WHERE it looked rather than only that it failed.
719
+ _tried=""
720
+ for _tier in "${HOOK_ADAPTER_DIR_TIERS[@]}"; do
721
+ _tier_id="${_tier%%|*}"
722
+ _tier_rest="${_tier#*|}"
723
+ _tier_base="${_tier_rest%%|*}"
724
+ _tier_dir="$(_hook_tier_dir "$_tier_id" "$_tier_base")"
725
+ _tried="$_tried $_tier_id=${_tier_dir:-<unset>}"
726
+ done
727
+ echo "⚠️ adapter-common.sh not found in any tier:${_tried}"
548
728
  echo "⚠️ Could not source adapter-common.sh. SKIP — Gate M."
549
- GATE_M_SKIP_REASON="adapter-common.sh could not be sourced"
550
- }
729
+ GATE_M_SKIP_REASON="adapter-common.sh not found in any resolution tier:$_tried"
730
+ GATE_M_SKIP_KIND="missing"
731
+ fi
551
732
 
552
733
  # #404 P0: every Gate M skip records WHY. Without this the journals carried
553
734
  # `details: {}` on 62 of 68 runs, so the RFC's "SKIP rate" question was
@@ -556,12 +737,14 @@ source "$ADAPTER_COMMON" 2>/dev/null || {
556
737
  if [[ ! -f "package.json" ]] || [[ ! -f "tsconfig.json" ]]; then
557
738
  echo "📚 Not a TypeScript project. SKIP — Gate M."
558
739
  GATE_M_SKIP_REASON="not a TypeScript project (package.json+tsconfig.json required)"
740
+ GATE_M_SKIP_KIND="not_applicable"
559
741
  else
560
742
  # Check if mutation testing is configured
561
743
  if ! detect_mutation_testable 2>/dev/null; then
562
744
  echo "⚠️ Stryker config not found or @stryker-mutator not installed."
563
745
  echo " SKIP — Gate M mutation testing."
564
746
  GATE_M_SKIP_REASON="stryker config missing or @stryker-mutator not installed"
747
+ GATE_M_SKIP_KIND="tool_missing"
565
748
  else
566
749
  # Filter to source files (exclude tests). The tree-segment grep excludes
567
750
  # test infrastructure (helpers/fixtures under tests/, test/, __tests__/)
@@ -572,6 +755,7 @@ else
572
755
  if [ -z "$CHANGED_SOURCE_FILES" ]; then
573
756
  echo "📚 No changed TypeScript source files. SKIP — Gate M."
574
757
  GATE_M_SKIP_REASON="no changed TypeScript source files in this push"
758
+ GATE_M_SKIP_KIND="no_input"
575
759
  else
576
760
  echo "🧬 Running mutation tests on changed files..."
577
761
  echo "$CHANGED_SOURCE_FILES"
@@ -589,6 +773,7 @@ else
589
773
  if [[ -z "$MUTATION_SCRIPT" ]]; then
590
774
  echo "⚠️ Gate M script not found. SKIP — Gate M."
591
775
  GATE_M_SKIP_REASON="gate-m.ts not found in .xp-gate/modules, src/mutation, or global modules"
776
+ GATE_M_SKIP_KIND="module_missing"
592
777
  else
593
778
  # Run mutation gate with timeout matching stryker.conf.json (timeoutMS: 600000 = 10min)
594
779
  MUTATION_OUTPUT=$(mktemp)
@@ -641,6 +826,7 @@ else
641
826
  echo " Allowing push with warning — review mutation coverage manually."
642
827
  GATE_M_STATUS="TIMEOUT"
643
828
  GATE_M_SKIP_REASON="mutation run exceeded the 600s timeout; score is unknown"
829
+ GATE_M_SKIP_KIND="timeout"
644
830
  ;;
645
831
  *)
646
832
  echo "⚠️ Gate M: Unexpected exit code $MUTATION_EXIT"
@@ -648,6 +834,7 @@ else
648
834
  echo " Allowing push with warning."
649
835
  GATE_M_STATUS="WARN"
650
836
  GATE_M_SKIP_REASON="gate-m.ts exited $MUTATION_EXIT (unexpected); score is unknown"
837
+ GATE_M_SKIP_KIND="error"
651
838
  ;;
652
839
  esac
653
840
 
@@ -0,0 +1,190 @@
1
+ /**
2
+ * @test REQ-DEPLOY-003 项目级默认架构配置
3
+ * @intent Gate 6 自 2026-05-04 起对「没有架构配置文件」的项目**直接阻塞提交**
4
+ * (`githooks/pre-commit:4838`:`echo "❌ ARCHITECTURE CONFIG MISSING - COMMIT BLOCKED"`)。
5
+ * 实测该判定只看文件是否**存在**(`-f` 三连),不解析内容。于是 `xp-gate init`
6
+ * 装好了全部 gate,却因为少一个文件让每一次提交都被拦——而且拦住的原因
7
+ * 与用户代码无关。本 REQ 让项目级 init 生成该文件。
8
+ *
9
+ * 两个用户决策不可推翻:
10
+ * 1. 只在**项目级** init 生成;全局安装**不写**用户 HOME。
11
+ * 2. 生成内容只含注释、零配置键——因为实测证明 `rules:` 与 `ignore:`
12
+ * 在 archlint 0.16.0 下都被静默忽略(设计文档 §3.4 实验 D/E),
13
+ * 写一个会被忽略的配置等于制造虚假安全感。
14
+ * @covers AC-DEPLOY-003-01, AC-DEPLOY-003-02, AC-DEPLOY-003-03,
15
+ * AC-DEPLOY-003-04, AC-DEPLOY-003-05, AC-DEPLOY-003-06,
16
+ * AC-DEPLOY-003-07, AC-DEPLOY-003-08
17
+ */
18
+ 'use strict';
19
+
20
+ const fs = require('node:fs');
21
+ const os = require('node:os');
22
+ const path = require('node:path');
23
+
24
+ // src/npm-package/lib/__tests__/ -> lib/ -> npm-package/ -> src/ -> <repo root>
25
+ const REPO_ROOT = path.resolve(__dirname, '..', '..', '..', '..');
26
+
27
+ const TEMPLATE_MODULE = path.join(REPO_ROOT, 'src', 'npm-package', 'lib', 'arch-config-template.js');
28
+ const CONFIG_FILENAME = '.archlint.yaml';
29
+
30
+ describe('REQ-DEPLOY-003 项目级默认架构配置', () => {
31
+ describe('AC-DEPLOY-003-01: 模板是唯一来源常量', () => {
32
+ it('arch-config-template.js 存在并导出 ARCH_CONFIG_TEMPLATE', () => {
33
+ expect(fs.existsSync(TEMPLATE_MODULE)).toBe(true);
34
+ const mod = require(TEMPLATE_MODULE);
35
+ expect(typeof mod.ARCH_CONFIG_TEMPLATE).toBe('string');
36
+ expect(mod.ARCH_CONFIG_TEMPLATE.length).toBeGreaterThan(0);
37
+ });
38
+
39
+ it('导出的模块对象被冻结,防止运行时被改写', () => {
40
+ const mod = require(TEMPLATE_MODULE);
41
+ // 断言的是**模块导出对象**冻结(不是字符串字面量——字符串本身不可变,
42
+ // 对它的 Object.isFrozen 断言永远为 false,等于没断言)。
43
+ expect(Object.isFrozen(mod)).toBe(true);
44
+ expect(typeof mod.ARCH_CONFIG_TEMPLATE).toBe('string');
45
+ });
46
+
47
+ it('导出 CONFIG_FILENAME,避免"文件名"在多个文件里各写一份', () => {
48
+ const mod = require(TEMPLATE_MODULE);
49
+ expect(mod.CONFIG_FILENAME).toBe('.archlint.yaml');
50
+ });
51
+ });
52
+
53
+ describe('AC-DEPLOY-003-02: 生成内容零配置键(实测 rules:/ignore: 均被忽略)', () => {
54
+ it('除注释行与空行外没有任何内容', () => {
55
+ const { ARCH_CONFIG_TEMPLATE } = require(TEMPLATE_MODULE);
56
+ const nonCommentLines = ARCH_CONFIG_TEMPLATE
57
+ .split('\n')
58
+ .map((l) => l.trim())
59
+ .filter((l) => l.length > 0 && !l.startsWith('#'));
60
+
61
+ // 这是 §3.4 的结论被写成断言:文件不配置任何东西。
62
+ // 实测(设计文档实验 D):`ignore: ["src/b.ts"]` 在 archlint 0.16.0 下
63
+ // files_analyzed 仍是 2、cyclic_dependencies 仍是 1 —— 配置被静默忽略。
64
+ expect(nonCommentLines).toEqual([]);
65
+ });
66
+
67
+ it('不含 rules: / ignore: / entry_points: 三个已知会被误读的顶层键', () => {
68
+ const { ARCH_CONFIG_TEMPLATE } = require(TEMPLATE_MODULE);
69
+ const nonComment = ARCH_CONFIG_TEMPLATE
70
+ .split('\n')
71
+ .filter((l) => !l.trim().startsWith('#'));
72
+ const joined = nonComment.join('\n');
73
+ expect(joined).not.toMatch(/^\s*rules:/m);
74
+ expect(joined).not.toMatch(/^\s*ignore:/m);
75
+ expect(joined).not.toMatch(/^\s*entry_points:/m);
76
+ });
77
+ });
78
+
79
+ describe('AC-DEPLOY-003-03: 注释说明为什么是空的、以及如何验证', () => {
80
+ it('说明里包含可执行的核查指引', () => {
81
+ const { ARCH_CONFIG_TEMPLATE } = require(TEMPLATE_MODULE);
82
+ // 新增文案契约:这个字符串是本设计要写的内容,不是对既有输出的观测。
83
+ expect(ARCH_CONFIG_TEMPLATE).toContain('archlint detectors list');
84
+ expect(ARCH_CONFIG_TEMPLATE).toMatch(/deliberately contains no configuration keys/i);
85
+ });
86
+
87
+ it('说明里解释了 Gate 6 只检查存在性(否则读者会以为配置已生效)', () => {
88
+ const { ARCH_CONFIG_TEMPLATE } = require(TEMPLATE_MODULE);
89
+ expect(ARCH_CONFIG_TEMPLATE).toMatch(/Gate 6/);
90
+ expect(ARCH_CONFIG_TEMPLATE).toMatch(/exist|存在/i);
91
+ });
92
+ });
93
+
94
+ describe('AC-DEPLOY-003-04: 生成内容会被 archlint 接受(解析不报错)', () => {
95
+ it('全注释文档是合法 YAML——js-yaml 会报"空文档",那是规范内行为', () => {
96
+ const { ARCH_CONFIG_TEMPLATE } = require(TEMPLATE_MODULE);
97
+ const yaml = require('js-yaml');
98
+ // 实测:js-yaml.load() 对全注释文档抛
99
+ // "expected a document, but the input is empty"
100
+ // 这不是语法错误,是"文档为空"的规范内结论(YAML 规范允许空文档)。
101
+ // 断言"要么解析出空值,要么抛这条特定的空文档错误",而不是假装它会返回 null。
102
+ let parsed;
103
+ let emptyDocumentError = null;
104
+ try {
105
+ parsed = yaml.load(ARCH_CONFIG_TEMPLATE);
106
+ } catch (e) {
107
+ emptyDocumentError = e.message;
108
+ }
109
+ if (emptyDocumentError === null) {
110
+ expect(parsed === null || parsed === undefined).toBe(true);
111
+ } else {
112
+ expect(emptyDocumentError).toMatch(/empty/i);
113
+ }
114
+ });
115
+ });
116
+
117
+ describe('AC-DEPLOY-003-08: 生成的文件真的让 Gate 6 的存在性判定成立', () => {
118
+ it('写到临时目录后,pre-commit 使用的三个 -f 判定至少命中一个', () => {
119
+ const { ARCH_CONFIG_TEMPLATE, CONFIG_FILENAME } = require(TEMPLATE_MODULE);
120
+ const tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'archcfg-'));
121
+ try {
122
+ const target = path.join(tmp, CONFIG_FILENAME);
123
+ fs.writeFileSync(target, ARCH_CONFIG_TEMPLATE, 'utf8');
124
+
125
+ // 逐字对应 githooks/pre-commit:4376 的三个判定
126
+ const hit = fs.existsSync(path.join(tmp, 'architecture.yaml'))
127
+ || fs.existsSync(path.join(tmp, '.architecturerc'))
128
+ || fs.existsSync(path.join(tmp, '.archlint.yaml'));
129
+ expect(hit).toBe(true);
130
+ } finally {
131
+ fs.rmSync(tmp, { recursive: true, force: true });
132
+ }
133
+ });
134
+ });
135
+
136
+ describe('AC-DEPLOY-003-05: 只在项目级 init 生成,全局安装不写 HOME', () => {
137
+ it('init.js 中写 .archlint.yaml 的代码只在 installLocal 路径上', () => {
138
+ const initSource = fs.readFileSync(
139
+ path.join(REPO_ROOT, 'src', 'npm-package', 'lib', 'init.js'),
140
+ 'utf8',
141
+ );
142
+ // 引用了模板模块
143
+ expect(initSource).toMatch(/arch-config-template/);
144
+ /**
145
+ * 断言的是**调用关系**,不是"函数体里出现过 archlint 这个词"。
146
+ * 后者会误报:installLocal 结尾的 FIRST-CLASS TEST QUALITY 提示里就有
147
+ * `.archlint.yaml ignore` 这行文案,与写入逻辑毫无关系。
148
+ */
149
+ const setupGlobalStart = initSource.search(
150
+ /(?:async\s+)?function\s+setupGlobal\s*\(/,
151
+ );
152
+ expect(setupGlobalStart).toBeGreaterThan(-1);
153
+ const afterSetupGlobal = initSource.slice(setupGlobalStart);
154
+ expect(afterSetupGlobal).not.toMatch(/ensureArchConfig\s*\(/);
155
+ });
156
+
157
+ it('ensureArchConfig 在 installLocal 内被调用', () => {
158
+ const initSource = fs.readFileSync(
159
+ path.join(REPO_ROOT, 'src', 'npm-package', 'lib', 'init.js'),
160
+ 'utf8',
161
+ );
162
+ const installLocalStart = initSource.search(/async\s+function\s+installLocal\s*\(/);
163
+ const setupGlobalStart = initSource.search(
164
+ /(?:async\s+)?function\s+setupGlobal\s*\(/,
165
+ );
166
+ expect(installLocalStart).toBeGreaterThan(-1);
167
+ const installLocalBody = initSource.slice(installLocalStart, setupGlobalStart);
168
+ expect(installLocalBody).toMatch(/ensureArchConfig\s*\(/);
169
+ });
170
+
171
+ it('模板模块本身不引用 HOME 或任何全局路径', () => {
172
+ const source = fs.readFileSync(TEMPLATE_MODULE, 'utf8');
173
+ expect(source).not.toMatch(/process\.env\.HOME|os\.homedir\(\)/);
174
+ });
175
+ });
176
+
177
+ describe('AC-DEPLOY-003-06: 已有配置文件时不覆盖', () => {
178
+ it('init 的写入逻辑带存在性守卫(不覆盖用户配置)', () => {
179
+ const initSource = fs.readFileSync(
180
+ path.join(REPO_ROOT, 'src', 'npm-package', 'lib', 'init.js'),
181
+ 'utf8',
182
+ );
183
+ // 必须能找到 existsSync 守卫与 .archlint.yaml 的关联
184
+ const mentions = [...initSource.matchAll(/archlint/g)];
185
+ expect(mentions.length).toBeGreaterThan(0);
186
+ // 守卫断言:写入点前后存在 existsSync 检查
187
+ expect(initSource).toMatch(/existsSync/);
188
+ });
189
+ });
190
+ });
@@ -0,0 +1,60 @@
1
+ /**
2
+ * @test REQ-GATE-SHELL-SCOPE The baseline must measure the same shell files the gate does
3
+ * @intent `createBaseline()` collected shell sources with `findFilesByExt(['.sh'])`,
4
+ * i.e. a git ls-files glob for the .sh extension. Much like the
5
+ * adapter's non-recursive double-star pattern, that cannot see
6
+ * `pre-commit` / `pre-push`, which carry no extension and are the two
7
+ * largest shell programs in this repository.
8
+ *
9
+ * The consequence is a baseline whose denominator is smaller than the
10
+ * gate's: warnings inside the hooks were never recorded, so the Boy
11
+ * Scout comparison could only ever say "debt unchanged" no matter what
12
+ * those files accumulated.
13
+ *
14
+ * @covers AC-GATE-SHELL-SCOPE-03
15
+ */
16
+ const path = require('path');
17
+ const { findShellScripts } = require('../baseline.js');
18
+
19
+ describe('baseline.js - shell scope', () => {
20
+ it('AC-GATE-SHELL-SCOPE-03: includes extensionless git hooks', () => {
21
+ const files = findShellScripts();
22
+
23
+ // This repository always has these two, and they have no .sh suffix.
24
+ const names = files.map(f => path.basename(f));
25
+ expect(names).toEqual(expect.arrayContaining(['pre-commit', 'pre-push']));
26
+ });
27
+
28
+ it('AC-GATE-SHELL-SCOPE-03: includes ordinary .sh files', () => {
29
+ const files = findShellScripts();
30
+ const sh = files.filter(f => f.endsWith('.sh'));
31
+
32
+ expect(sh.length).toBeGreaterThan(0);
33
+ });
34
+
35
+ it('AC-GATE-SHELL-SCOPE-03: does not include non-shell files', () => {
36
+ const files = findShellScripts();
37
+
38
+ for (const f of files) {
39
+ expect(f).not.toMatch(/\.(md|json|ts|js|py)$/);
40
+ }
41
+ });
42
+
43
+ it('AC-GATE-SHELL-SCOPE-03: returns an empty array outside a git work tree', () => {
44
+ const fs = require('fs');
45
+ const os = require('os');
46
+ const tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'baseline-shell-scope-'));
47
+ const originalCwd = process.cwd;
48
+
49
+ process.cwd = () => tmp;
50
+ try {
51
+ // Must degrade to an empty list, never throw: a baseline that crashes on
52
+ // a non-git directory breaks every `xp-gate baseline create` run there.
53
+ expect(() => findShellScripts()).not.toThrow();
54
+ expect(findShellScripts()).toEqual([]);
55
+ } finally {
56
+ process.cwd = originalCwd;
57
+ fs.rmSync(tmp, { recursive: true, force: true });
58
+ }
59
+ });
60
+ });
@@ -69,8 +69,19 @@ describe('crap-cli.js - advisory contract', () => {
69
69
  // Without coverage every function is unmeasured; printing an empty ranking
70
70
  // would read as "nothing to fix", which is the opposite of the truth.
71
71
  const missing = path.join(tmpDir, 'does-not-exist.json');
72
- const res = await capture(() => handleCrap(['--coverage', missing]));
73
- expect(res.code).toBe(1);
74
- expect(res.err).toContain('No coverage artifact');
72
+ // `--paths` is pinned at this empty temp dir on purpose. handleCrap runs
73
+ // lizard BEFORE it checks for the coverage artifact, so the default
74
+ // `--paths src` makes this case scan the whole source tree (measured 36.3 s)
75
+ // to reach an assertion that never looks at the scan. An empty directory
76
+ // makes lizard return in ~0.9 s with no output, which is all this case
77
+ // needs: it asserts the exit code and the message, nothing about the scan.
78
+ const emptyTree = fs.mkdtempSync(path.join(os.tmpdir(), 'crap-cli-empty-'));
79
+ try {
80
+ const res = await capture(() => handleCrap(['--coverage', missing, '--paths', emptyTree]));
81
+ expect(res.code).toBe(1);
82
+ expect(res.err).toContain('No coverage artifact');
83
+ } finally {
84
+ fs.rmSync(emptyTree, { recursive: true, force: true });
85
+ }
75
86
  });
76
87
  });