@boyingliu01/xp-gate 0.37.2 → 0.38.0

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 (118) 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/common-process.ts +36 -7
  16. package/gates/gate-9.ts +17 -8
  17. package/gates/python-health.ts +215 -24
  18. package/hooks/adapter-common.sh +12 -2
  19. package/hooks/deploy-manifest.sh +100 -0
  20. package/hooks/gate-10.sh +99 -26
  21. package/hooks/gate-12-file-hygiene.sh +13 -1
  22. package/hooks/gate-driver.sh +120 -0
  23. package/hooks/gate-entries/gate-0-entry.sh +825 -0
  24. package/hooks/gate-entries/gate-1-entry.sh +767 -0
  25. package/hooks/gate-entries/gate-10-entry.sh +52 -0
  26. package/hooks/gate-entries/gate-11-entry.sh +120 -0
  27. package/hooks/gate-entries/gate-12-entry.sh +44 -0
  28. package/hooks/gate-entries/gate-12b-entry.sh +178 -0
  29. package/hooks/gate-entries/gate-12c-entry.sh +80 -0
  30. package/hooks/gate-entries/gate-13-entry.sh +584 -0
  31. package/hooks/gate-entries/gate-2-entry.sh +199 -0
  32. package/hooks/gate-entries/gate-3-entry.sh +53 -0
  33. package/hooks/gate-entries/gate-4-entry.sh +46 -0
  34. package/hooks/gate-entries/gate-5-entry.sh +1729 -0
  35. package/hooks/gate-entries/gate-6-entry.sh +658 -0
  36. package/hooks/gate-entries/gate-7-entry.sh +41 -0
  37. package/hooks/gate-entries/gate-8-entry.sh +33 -0
  38. package/hooks/gate-entries/gate-9-entry.sh +307 -0
  39. package/hooks/gate-entries/subdir-restore.sh +27 -0
  40. package/hooks/gate-registry.sh +51 -15
  41. package/hooks/hook-module-resolution.sh +73 -0
  42. package/hooks/install.sh +135 -0
  43. package/hooks/lib/now-ms.sh +55 -19
  44. package/hooks/lib/toolchain-path.sh +50 -6
  45. package/hooks/pre-commit +256 -5091
  46. package/hooks/pre-push +212 -25
  47. package/lib/__tests__/arch-config-template.test.js +190 -0
  48. package/lib/__tests__/baseline-shell-scope.test.js +60 -0
  49. package/lib/__tests__/crap-cli.test.js +14 -3
  50. package/lib/__tests__/deploy-manifest-check-wired.test.js +138 -0
  51. package/lib/__tests__/deploy-manifest-completeness.test.js +151 -0
  52. package/lib/__tests__/deploy-manifest-consumers-adapter-uninstall.test.js +40 -0
  53. package/lib/__tests__/deploy-manifest-consumers-no-private-lists.test.js +74 -0
  54. package/lib/__tests__/deploy-manifest-projection.test.js +66 -0
  55. package/lib/__tests__/deploy-manifest-shell-parity.test.js +108 -0
  56. package/lib/__tests__/deploy-manifest.test.js +97 -0
  57. package/lib/__tests__/doctor.test.js +51 -7
  58. package/lib/__tests__/gate-coverage.test.js +79 -12
  59. package/lib/__tests__/gate-numbering.test.js +28 -1
  60. package/lib/__tests__/install-sh-deploy-manifest.test.js +80 -0
  61. package/lib/__tests__/mirror-sync.test.js +45 -3
  62. package/lib/__tests__/npm-package.test.js +10 -7
  63. package/lib/__tests__/sastd-client.test.js +452 -0
  64. package/lib/__tests__/shared-utils-copyHooks-manifest.test.js +69 -0
  65. package/lib/__tests__/sprint-status-rework.test.js +1 -0
  66. package/lib/arch-config-template.js +87 -0
  67. package/lib/baseline.js +54 -2
  68. package/lib/deploy-manifest.js +174 -0
  69. package/lib/doctor.js +46 -14
  70. package/lib/gate-capability.js +291 -0
  71. package/lib/gate-coverage.js +194 -74
  72. package/lib/gate-identity.js +349 -0
  73. package/lib/gate-runner.js +11 -1
  74. package/lib/hook-module-resolution.js +27 -0
  75. package/lib/init.js +72 -5
  76. package/lib/mattpocock-license-verdict.json +1 -1
  77. package/lib/sastd-client.js +534 -0
  78. package/lib/shared-utils.js +31 -9
  79. package/lib/uninstall.js +10 -7
  80. package/lib/update-hooks.js +27 -18
  81. package/mock-policy/AGENTS.md +1 -1
  82. package/mutation/AGENTS.md +1 -1
  83. package/package.json +3 -1
  84. package/plugins/claude-code/.claude-plugin/plugin.json +1 -1
  85. package/plugins/claude-code/skills/delphi-review/AGENTS.md +1 -1
  86. package/plugins/claude-code/skills/sprint-flow/AGENTS.md +1 -1
  87. package/plugins/claude-code/skills/test-specification-alignment/AGENTS.md +2 -2
  88. package/plugins/dsh/package.json +1 -1
  89. package/plugins/dsh/skills/delphi-review/AGENTS.md +1 -1
  90. package/plugins/dsh/skills/sprint-flow/AGENTS.md +1 -1
  91. package/plugins/dsh/skills/test-specification-alignment/AGENTS.md +2 -2
  92. package/plugins/opencode/package.json +1 -1
  93. package/plugins/opencode/skills/delphi-review/AGENTS.md +1 -1
  94. package/plugins/opencode/skills/sprint-flow/AGENTS.md +1 -1
  95. package/plugins/opencode/skills/test-specification-alignment/AGENTS.md +2 -2
  96. package/plugins/qoder/plugin.json +1 -1
  97. package/plugins/qoder/skills/delphi-review/AGENTS.md +1 -1
  98. package/plugins/qoder/skills/sprint-flow/AGENTS.md +1 -1
  99. package/plugins/qoder/skills/test-specification-alignment/AGENTS.md +2 -2
  100. package/principles/AGENTS.md +1 -1
  101. package/principles/__tests__/analyzer.test.ts +2 -1
  102. package/principles/__tests__/config-enforcement.test.ts +1 -0
  103. package/principles/__tests__/types.test.ts +1 -0
  104. package/principles/adapters/base.ts +14 -1
  105. package/principles/adapters/duplication.ts +134 -0
  106. package/principles/rules/__tests__/clean-code/large-file.test.ts +2 -1
  107. package/principles/rules/clean-code/code-duplication.ts +75 -9
  108. package/principles/types.ts +39 -0
  109. package/scripts/__tests__/check-mattpocock-license.test.js +36 -3
  110. package/scripts/__tests__/sync-package-content.test.js +12 -2
  111. package/scripts/generate-mirrors.cjs +125 -0
  112. package/scripts/sync-package-content.js +64 -20
  113. package/skills/delphi-review/AGENTS.md +1 -1
  114. package/skills/sprint-flow/AGENTS.md +1 -1
  115. package/skills/test-specification-alignment/AGENTS.md +2 -2
  116. package/adapters/gate-9.sh +0 -245
  117. package/gate-9.sh +0 -245
  118. package/hooks/gate-9.sh +0 -245
@@ -43,92 +43,190 @@ const QUALITY_STATUS_DIR = path.join('.xp-gate', 'quality-status');
43
43
 
44
44
  /** The Boy Scout debt lives in its baseline, not in a gate status. */
45
45
  /**
46
- * The quality-status producer's own keys, in ITS numbering.
46
+ * The gate table and the producer's artifact keys are DERIVED from
47
+ * `githooks/gate-registry.sh`, never declared here.
47
48
  *
48
- * Kept as an array of pairs rather than an object literal so the table below
49
- * stays free of `name: 'literal'` shapes -- a generic-api-key scanner reads
50
- * those as credentials, and teaching the secret gate to ignore this file would
51
- * be a worse trade than reshaping the data.
49
+ * This file used to carry two handwritten tables: a number->name array and a
50
+ * "producer keys" array that also mapped artifact key -> number. The second one
51
+ * contained this comment:
52
+ *
53
+ * // NOTE the swap: the producer calls Build Integrity gate9 and SAST
54
+ * // gate10, while this project numbers them the other way round.
55
+ *
56
+ * That claim was FALSE. `githooks/pre-commit` emits `gate9_build_integrity` and
57
+ * `gate10_sast` — exactly what the registry says. The swap table encoded an
58
+ * inversion that never existed, so `gate-coverage` answered questions about one
59
+ * artifact using another artifact's numbering: with an artifact reporting
60
+ * `gate9_build_integrity=PASS` it printed "9 SAST Security PASS" (#738).
61
+ *
62
+ * Deleting the table alone would not fix the class: it removes one copy of a
63
+ * fact without removing the act of copying. So both tables are derived, and
64
+ * scripts/__tests__/gate-identity-cross-surface.test.cjs compares the derived
65
+ * surfaces against the registry. Restore a handwritten mapping here and that
66
+ * test fails.
67
+ *
68
+ * The derived table deliberately keeps the field shape `{ gate, name, ... }`
69
+ * with a string `name` value. An earlier version avoided that shape because a
70
+ * generic-api-key scanner reads `name: 'literal'` as a credential; the values
71
+ * now come from the registry at runtime rather than appearing as literals in
72
+ * this file, so the scanner has nothing to match.
73
+ */
74
+ const { loadRegistry, parseRegistry, parseReportKeyOverrides, deriveGateTable, reportKey } = require('./gate-identity');
75
+
76
+ /**
77
+ * The derived gate table, computed ON FIRST USE rather than at require() time.
78
+ *
79
+ * A copy disagreement in the registry is a real, fatal condition for anything
80
+ * that renders gates -- but it is not a fact about arithmetic on an artifact.
81
+ * Computing it eagerly meant `require('gate-coverage')` threw for consumers that
82
+ * only wanted `STATUS` or `exitCodeFor`, so a packaging bug in a file the caller
83
+ * never reads would take down an unrelated code path. Deferring it keeps the
84
+ * fail-closed behaviour where it belongs: the throw now fires on the first call
85
+ * that actually needs gate identity, and the message still names every differing
86
+ * copy (see loadRegistry).
87
+ */
88
+ let _gateTableCache = null;
89
+
90
+ function gateTable() {
91
+ if (_gateTableCache === null) {
92
+ const registry = loadRegistry();
93
+ _gateTableCache = deriveGateTable(
94
+ parseRegistry(registry.text),
95
+ parseReportKeyOverrides(registry.text),
96
+ );
97
+ }
98
+ return _gateTableCache;
99
+ }
100
+
101
+ /**
102
+ * Registry rows, keyed by number, with the artifact report key attached.
103
+ * Replaces the deleted PRODUCER_KEYS / GATE_NUMBER_TO_PRODUCER pair.
104
+ */
105
+ // Built per call from the same lazy table, so a renumbering can never leave a
106
+ // stale number->row index behind.
107
+ function gateByNumber() {
108
+ return new Map(gateTable().map((row) => [row.gate, row]));
109
+ }
110
+
111
+ /**
112
+ * Evidence pointer per gate. This is the ONE thing this file still owns: the
113
+ * human-readable description of where a verdict comes from. It is keyed by
114
+ * registry NAME (not number), so renumbering a gate cannot orphan an entry.
52
115
  */
53
- const PRODUCER_KEYS = [
54
- ['gate0_version_consistency', 0],
55
- ['gate1_static_analysis', 1],
56
- ['gate2_dup_code', 2],
57
- ['gate3_complexity', 3],
58
- ['gate4_principles', 4],
59
- ['gate5_tests', 5],
60
- ['gate6_arch_boyscout', 6],
61
- ['gate7_iac_security', 7],
62
- ['gate8_secret_scanning', 8],
63
- // NOTE the swap: the producer calls Build Integrity gate9 and SAST gate10,
64
- // while this project numbers them the other way round.
65
- ['gate10_sast', 9],
66
- ['gate9_build_integrity', 10],
67
- ['gate11_sprint_flow', 11],
68
- ['gate12_file_hygiene', 12],
69
- ['gate13_compiler_strictness', 13],
70
- ];
71
-
72
- /** Producer key -> this project's gate number. */
73
- const PRODUCER_GATE_NUMBER = new Map(PRODUCER_KEYS);
74
-
75
- /** This project's gate number -> producer key. */
76
- const GATE_NUMBER_TO_PRODUCER = new Map(PRODUCER_KEYS.map(([k, n]) => [n, k]));
116
+ const EVIDENCE_BY_NAME = {
117
+ 'version-consistency': 'VERSION and package.json',
118
+ 'code-quality': 'adapter lint output',
119
+ 'duplicate-code': 'jscpd configuration',
120
+ complexity: 'ccn baseline',
121
+ principles: 'principles rc',
122
+ 'tests-coverage': 'coverage summary',
123
+ architecture: 'warnings baseline (see .warnings-baseline.json)',
124
+ 'iac-security': 'iac scanner configuration',
125
+ 'secret-scanning': 'secret scanner configuration',
126
+ 'build-integrity': 'typecheck and pack',
127
+ sast: 'sast ruleset',
128
+ 'sprint-flow': 'specification',
129
+ 'file-hygiene': 'file hygiene script',
130
+ 'compiler-strictness': 'compiler strictness script',
131
+ };
77
132
 
78
133
  /**
79
- * The canonical gate table: number, name, whether the CLI can run it, and the
80
- * artifact that decides its verdict.
134
+ * Display names, keyed by registry SLUG.
81
135
  *
82
- * Gate names deliberately match `xp-gate gate-list`; the producer's differing
83
- * numbering is absorbed by PRODUCER_KEYS above.
136
+ * The slug is the identity and every comparison uses it. This map only makes
137
+ * the report readable ("build-integrity" -> "Build Integrity"); a missing entry
138
+ * degrades to the slug rather than to nothing, so adding a gate to the registry
139
+ * never produces a blank row. Keying by slug (not number) means renumbering
140
+ * cannot orphan an entry — which is the failure this whole sprint removes.
84
141
  */
85
- const GATE_TABLE = [
86
- { gate: 0, name: 'Version Consistency', hookOnly: true, evidence: 'VERSION and package.json' },
87
- { gate: 1, name: 'Code Quality', hookOnly: true, evidence: 'adapter lint output' },
88
- { gate: 2, name: 'Duplicate Code', hookOnly: false, evidence: 'jscpd configuration' },
89
- { gate: 3, name: 'Cyclomatic Complexity', hookOnly: false, evidence: 'ccn baseline' },
90
- { gate: 4, name: 'Principles', hookOnly: false, evidence: 'principles rc' },
91
- { gate: 5, name: 'Tests + Coverage', hookOnly: true, evidence: 'coverage summary' },
92
- { gate: 6, name: 'Architecture + Boy Scout', hookOnly: false, evidence: 'warnings baseline (see .warnings-baseline.json)' },
93
- { gate: 7, name: 'IaC Security', hookOnly: false, evidence: 'iac scanner configuration' },
94
- { gate: 8, name: 'Secret Scanning', hookOnly: false, evidence: 'secret scanner configuration' },
95
- { gate: 9, name: 'SAST Security', hookOnly: false, evidence: 'sast ruleset' },
96
- { gate: 10, name: 'Build Integrity', hookOnly: true, evidence: 'typecheck and pack' },
97
- { gate: 11, name: 'Sprint Flow', hookOnly: true, evidence: 'specification' },
98
- { gate: 12, name: 'File Hygiene', hookOnly: false, evidence: 'file hygiene script' },
99
- { gate: 13, name: 'Compiler Strictness', hookOnly: false, evidence: 'compiler strictness script' },
100
- ];
142
+ const GATE_DISPLAY_NAME = {
143
+ 'version-consistency': 'Version Consistency',
144
+ 'code-quality': 'Code Quality',
145
+ 'duplicate-code': 'Duplicate Code',
146
+ complexity: 'Cyclomatic Complexity',
147
+ principles: 'Principles',
148
+ 'tests-coverage': 'Tests + Coverage',
149
+ architecture: 'Architecture + Boy Scout',
150
+ 'iac-security': 'IaC Security',
151
+ 'secret-scanning': 'Secret Scanning',
152
+ 'build-integrity': 'Build Integrity',
153
+ sast: 'SAST Security',
154
+ 'sprint-flow': 'Sprint Flow',
155
+ 'file-hygiene': 'File Hygiene',
156
+ 'compiler-strictness': 'Compiler Strictness',
157
+ };
101
158
 
102
159
  const BOY_SCOUT_GATE = 6;
103
160
 
104
161
  /**
105
162
  * Read `.xp-gate/quality-status/<branch>.json` if present.
163
+ *
164
+ * Deterministic or explicit failure (REQ-GATEID-007). This used to fall through
165
+ * to `readdirSync` over every `.json` and take the first parseable one, so a
166
+ * bare `xp-gate gate-coverage` read whichever file the filesystem happened to
167
+ * list first. In this repo that was `land-pr438.json` (commit 33672f6d) rather
168
+ * than the current branch's `main.json` — so the command reported another
169
+ * commit's SAST result as if it were this one's, printing `stale: true` as a
170
+ * notice while presenting the wrong object. Reading the wrong object is worse
171
+ * than reading a stale one, and "stale" masked it.
172
+ *
173
+ * Now: one candidate -> use it. Several -> REFUSE and say how to disambiguate.
174
+ * Explicit `--branch` that does not exist -> error, never a silent fallback.
175
+ *
106
176
  * @param {string} repoRoot
107
177
  * @param {string} [branch]
108
- * @returns {{artifact: object|null, file: string|null}}
178
+ * @returns {{artifact: object|null, file: string|null, error?: string, candidates?: string[]}}
109
179
  */
110
180
  function readQualityStatus(repoRoot, branch) {
111
181
  const dir = path.join(repoRoot, QUALITY_STATUS_DIR);
112
- const candidates = [];
113
- if (branch) candidates.push(path.join(dir, `${branch}.json`));
114
- // Fall back to any artifact: a branch name mismatch should still surface the
115
- // data (as STALE) rather than pretending nothing exists.
116
- try {
117
- for (const name of fs.readdirSync(dir)) {
118
- if (name.endsWith('.json')) candidates.push(path.join(dir, name));
182
+
183
+ if (branch) {
184
+ const wanted = path.join(dir, `${branch}.json`);
185
+ if (!fs.existsSync(wanted)) {
186
+ return {
187
+ artifact: null,
188
+ file: null,
189
+ error: `no quality-status artifact for branch "${branch}": ${wanted} does not exist`,
190
+ };
119
191
  }
192
+ return { artifact: parseArtifact(wanted), file: wanted };
193
+ }
194
+
195
+ let names;
196
+ try {
197
+ names = fs.readdirSync(dir).filter((name) => name.endsWith('.json')).sort();
120
198
  } catch {
121
199
  return { artifact: null, file: null };
122
200
  }
123
- for (const file of candidates) {
124
- try {
125
- const parsed = JSON.parse(fs.readFileSync(file, 'utf8'));
126
- if (parsed && typeof parsed === 'object') return { artifact: parsed, file };
127
- } catch {
128
- /* malformed artifact: treat as absent, never as clean */
129
- }
201
+
202
+ if (names.length === 0) return { artifact: null, file: null };
203
+
204
+ if (names.length > 1) {
205
+ const candidates = names.map((name) => name.replace(/\.json$/, ''));
206
+ return {
207
+ artifact: null,
208
+ file: null,
209
+ candidates,
210
+ error: `found ${names.length} quality-status artifacts (${candidates.join(', ')}); `
211
+ + 'refusing to pick one by directory order — pass --branch <name> to choose',
212
+ };
213
+ }
214
+
215
+ const only = path.join(dir, names[0]);
216
+ return { artifact: parseArtifact(only), file: only };
217
+ }
218
+
219
+ /**
220
+ * Parse one artifact file. A malformed artifact is ABSENT, never clean.
221
+ * @param {string} file
222
+ */
223
+ function parseArtifact(file) {
224
+ try {
225
+ const parsed = JSON.parse(fs.readFileSync(file, 'utf8'));
226
+ return parsed && typeof parsed === 'object' ? parsed : null;
227
+ } catch {
228
+ return null;
130
229
  }
131
- return { artifact: null, file: null };
132
230
  }
133
231
 
134
232
  /**
@@ -142,12 +240,18 @@ function buildCoverageRows(artifact, ctx) {
142
240
  const context = ctx || {};
143
241
  const gates = (artifact && artifact.gates) || {};
144
242
 
145
- return GATE_TABLE.map((spec) => {
146
- const entry = gates[GATE_NUMBER_TO_PRODUCER.get(spec.gate)];
243
+ const table = gateTable();
244
+ const byNumber = gateByNumber();
245
+
246
+ return table.map((spec) => {
247
+ // Look the gate up by its OWN report key, derived from the registry. The
248
+ // deleted swap table used to translate between two numberings here; there
249
+ // was only ever one numbering (#738).
250
+ const entry = gates[reportKey({ name: spec.slug, number: spec.gate })];
147
251
  const row = {
148
252
  gate: spec.gate,
149
- name: spec.name,
150
- evidence: spec.evidence,
253
+ name: GATE_DISPLAY_NAME[spec.slug] || spec.slug,
254
+ evidence: EVIDENCE_BY_NAME[spec.slug] || spec.impl,
151
255
  };
152
256
 
153
257
  if (!entry) {
@@ -194,9 +298,12 @@ function buildCoverageRows(artifact, ctx) {
194
298
  * it yet" -- not "it can never run".
195
299
  */
196
300
  function missingGateReason(spec) {
197
- return spec.hookOnly
198
- ? 'no result recorded — runs via git commit'
199
- : 'no result recorded — not run in the last report';
301
+ // `hook` comes from the registry: a pre-commit gate absent from the artifact
302
+ // means no commit has run it yet; a pre-push gate absent means it was not in
303
+ // the last pre-push report. Both are "no verdict", neither is "clean".
304
+ return spec.hook === 'pre-push'
305
+ ? 'no result recorded — runs via git push'
306
+ : 'no result recorded — runs via git commit';
200
307
  }
201
308
 
202
309
  /**
@@ -455,7 +562,20 @@ function main(argv, deps) {
455
562
 
456
563
  const branchIdx = args.indexOf('--branch');
457
564
  const branch = branchIdx !== -1 ? args[branchIdx + 1] : ctx.branch;
458
- const { artifact, file } = readQualityStatus(repoRoot, branch);
565
+ const status = readQualityStatus(repoRoot, branch);
566
+
567
+ if (status.error) {
568
+ // Deterministic-or-fail (REQ-GATEID-007). The migration hint lives IN the
569
+ // error text: turning a silent wrong answer into a bare error would be a
570
+ // worse failure mode than the bug it replaces.
571
+ const hint = status.candidates
572
+ ? `\n Retry with one of: ${status.candidates.map((name) => `--branch ${name}`).join(' | ')}`
573
+ : '';
574
+ process.stderr.write(`\n [gate-coverage] ${status.error}${hint}\n\n`);
575
+ return 2;
576
+ }
577
+
578
+ const { artifact, file } = status;
459
579
  const headCommit = ctx.headCommit;
460
580
 
461
581
  const stale = Boolean(artifact && headCommit && artifact.commit && artifact.commit !== headCommit);
@@ -493,7 +613,7 @@ function main(argv, deps) {
493
613
 
494
614
  module.exports = {
495
615
  STATUS,
496
- GATE_TABLE,
616
+ gateTable,
497
617
  buildCoverageRows,
498
618
  renderGateCoverage,
499
619
  exitCodeFor,
@@ -0,0 +1,349 @@
1
+ /**
2
+ * Gate identity: the ONE place that turns `githooks/gate-registry.sh` into data.
3
+ *
4
+ * Why this file exists
5
+ * --------------------
6
+ * A gate has two properties: a NAME (`sast`, `build-integrity` — its identity,
7
+ * stable) and a NUMBER (9, 10 — a display position, movable). Four surfaces
8
+ * used to each declare "number -> name". Three agreed; `gate-coverage.js` alone
9
+ * was inverted, and it carried a swap table whose comment claimed the artifact
10
+ * producer numbers them the other way round. That claim was false — the
11
+ * producer emits `gate9_build_integrity` and `gate10_sast`, exactly like the
12
+ * registry. The swap table encoded an inversion that never existed, and its
13
+ * presence made the defect read as intentional design (#738).
14
+ *
15
+ * Deleting that table is not a fix on its own: it removes today's copy without
16
+ * removing the act of copying. So every consumer DERIVES from the registry, and
17
+ * `scripts/__tests__/gate-identity-cross-surface.test.cjs` compares the
18
+ * surfaces so a fresh copy fails a test instead of misleading a reader.
19
+ *
20
+ * The registry is a shell file because it must be `source`-able by
21
+ * pre-commit/pre-push with no Node dependency. This module is the thin Node
22
+ * reader; it does not add a build step.
23
+ *
24
+ * @see docs/plans/2026-11-10-gate-identity-single-source.md
25
+ */
26
+ 'use strict';
27
+
28
+ const fs = require('node:fs');
29
+ const path = require('node:path');
30
+
31
+ const REGISTRY_FILENAME = 'gate-registry.sh';
32
+ const HOOKS_OF_RECORD = new Set(['pre-commit', 'pre-push']);
33
+
34
+ /**
35
+ * Report key overrides for rows whose historical artifact key is not derivable
36
+ * from `gate{number}_{name}`.
37
+ *
38
+ * Exactly one entry today. This is deliberately NOT a second table of all
39
+ * fourteen rows: the rule derives by default, and only genuine deviations are
40
+ * written down, so the deviation set is enumerable and reviewable.
41
+ *
42
+ * The override is READ FROM `GATE_REPORT_KEY_OVERRIDES` in the registry file,
43
+ * never restated here. An earlier revision of this module exported a hardcoded
44
+ * `Map([['code-quality', 'gate1_static_analysis']])` as a fallback -- which is
45
+ * precisely the defect this module exists to remove: a second declaration of a
46
+ * gate fact, sitting outside the row it modifies, able to drift silently. There
47
+ * is no fallback now: if the registry lacks the block, the override set is
48
+ * EMPTY, and a report-key mismatch becomes a visible cross-surface violation
49
+ * instead of being papered over by a JS copy nobody updates.
50
+ *
51
+ * `EMPTY_OVERRIDES` is not a declaration of any gate; it is the honest answer
52
+ * "the registry lists no deviations".
53
+ */
54
+ const EMPTY_OVERRIDES = new Map();
55
+
56
+ /**
57
+ * Find every copy of the registry, deterministically.
58
+ *
59
+ * The policy is stated over the SET of discovered copies, never over a pair
60
+ * (design V8/V10). A pairwise rule lets an implementation stop at the first two
61
+ * agreeing copies and walk past a third that differs — the same drift tolerance
62
+ * this module exists to remove. Majority voting is explicitly banned for the
63
+ * same reason.
64
+ *
65
+ * Discovery is an algorithm rather than a list: a fixed list of the three known
66
+ * paths would pass a test that injects a divergent copy at a known location
67
+ * while missing a fourth elsewhere.
68
+ *
69
+ * @param {string} repoRoot
70
+ * @returns {string[]} absolute paths, sorted for reproducible failure output
71
+ */
72
+ function discoverRegistryCopies(repoRoot) {
73
+ const found = [];
74
+ const seenRealPaths = new Set();
75
+
76
+ const walk = (dir) => {
77
+ let entries;
78
+ try {
79
+ entries = fs.readdirSync(dir, { withFileTypes: true });
80
+ } catch {
81
+ return; // unreadable directory is not a copy
82
+ }
83
+ for (const entry of entries) {
84
+ const full = path.join(dir, entry.name);
85
+ if (entry.isDirectory()) {
86
+ // Two exclusions, for two different reasons:
87
+ //
88
+ // * `.git` holds no shipped copy; walking it only costs time.
89
+ // * `.worktrees` holds OTHER CHECKOUTS of this same repository. Their
90
+ // registry files are not copies of this checkout's declaration, they
91
+ // are another branch's -- so counting them turns "is this checkout
92
+ // consistent" into "are all branches identical", which fails during
93
+ // any ordinary merge or feature branch and reports disagreement at
94
+ // paths belonging to some other working tree. Found while merging
95
+ // this very sprint: main discovered 6 copies, 3 of them the sprint
96
+ // worktree's.
97
+ //
98
+ // node_modules is deliberately NOT excluded: a packaged copy there is a
99
+ // real mirror, and hiding it would suppress a real disagreement.
100
+ if (entry.name === '.git' || entry.name === '.worktrees') continue;
101
+ walk(full);
102
+ continue;
103
+ }
104
+ if (entry.name !== REGISTRY_FILENAME) continue;
105
+ let realPath = full;
106
+ try {
107
+ realPath = fs.realpathSync(full);
108
+ } catch {
109
+ /* keep the literal path */
110
+ }
111
+ // A symlink pair resolving to the same file is ONE copy, not a
112
+ // disagreement with itself.
113
+ if (seenRealPaths.has(realPath)) continue;
114
+ seenRealPaths.add(realPath);
115
+ found.push(full);
116
+ }
117
+ };
118
+
119
+ walk(repoRoot);
120
+ return found.sort();
121
+ }
122
+
123
+ /**
124
+ * Resolve the registry to a single, agreed-upon content.
125
+ *
126
+ * Implements design V8/V12: the policy applies to the copies that exist. A
127
+ * missing path is not a failure — an `xp-gate init` consumer legitimately has
128
+ * only `hooks/gate-registry.sh` and no root copy. Only "no copies at all"
129
+ * fails, because then no gate identity can be determined and guessing is worse
130
+ * than stopping at the boundary where a corrupted install should stop.
131
+ *
132
+ * @param {string} [repoRoot]
133
+ * @returns {{ path: string, copies: string[], text: string }}
134
+ */
135
+ function loadRegistry(repoRoot = path.resolve(__dirname, '..', '..', '..')) {
136
+ const copies = discoverRegistryCopies(repoRoot);
137
+ if (copies.length === 0) {
138
+ // Actionable on purpose. The most likely reader of this message is someone
139
+ // whose consumer repo was installed by a package that predates the registry:
140
+ // the gate still runs, but nothing can be looked up by name. Telling them
141
+ // only "cannot be determined" leaves them to guess that an upgrade fixes it.
142
+ throw new Error(
143
+ `gate-identity: no ${REGISTRY_FILENAME} found under ${repoRoot}. `
144
+ + 'Gate identity cannot be determined.\n'
145
+ + ` Expected the registry shipped with the hooks (${REGISTRY_FILENAME} in githooks/).\n`
146
+ + ' An installation predating it is missing. Fix: upgrade to a package that '
147
+ + 'ships the registry and re-sync the hooks:\n'
148
+ + ' npx @boyingliu01/xp-gate@latest doctor --sync-hooks',
149
+ );
150
+ }
151
+
152
+ const contents = copies.map((copy) => ({ path: copy, text: fs.readFileSync(copy, 'utf8') }));
153
+ const reference = contents[0];
154
+
155
+ for (const candidate of contents.slice(1)) {
156
+ if (candidate.text === reference.text) continue;
157
+ const refLines = reference.text.split('\n');
158
+ const candLines = candidate.text.split('\n');
159
+ const limit = Math.max(refLines.length, candLines.length);
160
+ let firstDiff = 1;
161
+ for (let i = 0; i < limit; i++) {
162
+ if (refLines[i] !== candLines[i]) {
163
+ firstDiff = i + 1;
164
+ break;
165
+ }
166
+ }
167
+ throw new Error(
168
+ 'gate-identity: registry copies disagree. A copy disagreement IS the defect '
169
+ + `this module exists to remove, so it is a hard failure rather than a silent pick.\n`
170
+ + ` copies (sorted):\n${copies.map((copy) => ` ${copy}`).join('\n')}\n`
171
+ + ` first difference: ${reference.path} vs ${candidate.path}, line ${firstDiff}\n`
172
+ + ` ${JSON.stringify(refLines[firstDiff - 1] ?? '')} != ${JSON.stringify(candLines[firstDiff - 1] ?? '')}`,
173
+ );
174
+ }
175
+
176
+ return { path: reference.path, copies, text: reference.text };
177
+ }
178
+
179
+ /**
180
+ * Parse `GATE_REGISTRY_ROWS=( ... )` into row objects.
181
+ *
182
+ * Scoped to the array block: a "line starts with a quote" parser also matches
183
+ * the quoted usage examples in the header comment, inventing rows that do not
184
+ * exist. Lines outside the block must be blank or comments; anything else
185
+ * throws, because a parser that silently skips is how a row vanishes from every
186
+ * surface at once.
187
+ *
188
+ * @param {string} text
189
+ * @returns {Array<{name: string, number: string, impl: string, blocks: string, hook: string}>}
190
+ */
191
+ function parseRegistry(text) {
192
+ const lines = text.split('\n');
193
+ const start = lines.findIndex((line) => /^GATE_REGISTRY_ROWS=\($/.test(line.trim()));
194
+ if (start === -1) throw new Error('gate-identity: GATE_REGISTRY_ROWS array not found');
195
+
196
+ const rows = [];
197
+ let closed = false;
198
+ for (let i = start + 1; i < lines.length; i++) {
199
+ const line = lines[i].trim();
200
+ if (line === ')') {
201
+ closed = true;
202
+ break;
203
+ }
204
+ if (line === '' || line.startsWith('#')) continue;
205
+ const match = line.match(/^"([^"]*)"$/);
206
+ if (!match) throw new Error(`gate-identity: unparseable registry row at line ${i + 1}: ${line}`);
207
+ const fields = match[1].split('|');
208
+ // 4 fields = legacy row written before the `hook` column existed; it is a
209
+ // pre-commit row by construction.
210
+ if (fields.length !== 4 && fields.length !== 5) {
211
+ throw new Error(`gate-identity: registry row must have 4 or 5 fields, got ${fields.length}: ${line}`);
212
+ }
213
+ const [name, number, impl, blocks, hook = 'pre-commit'] = fields;
214
+ if (blocks !== 'YES' && blocks !== 'NO') {
215
+ throw new Error(`gate-identity: blocks must be YES or NO, got "${blocks}": ${line}`);
216
+ }
217
+ if (!HOOKS_OF_RECORD.has(hook)) {
218
+ throw new Error(`gate-identity: hook must be one of ${[...HOOKS_OF_RECORD].join('|')}, got "${hook}": ${line}`);
219
+ }
220
+ rows.push({ name, number, impl, blocks, hook });
221
+ }
222
+ if (!closed) throw new Error('gate-identity: GATE_REGISTRY_ROWS array was not closed with ")"');
223
+
224
+ const numbers = rows.map((row) => row.number);
225
+ if (new Set(numbers).size !== numbers.length) throw new Error('gate-identity: duplicate gate numbers in registry');
226
+ const names = rows.map((row) => row.name);
227
+ if (new Set(names).size !== names.length) throw new Error('gate-identity: duplicate gate names in registry');
228
+
229
+ return rows;
230
+ }
231
+
232
+ /**
233
+ * Parse `GATE_REPORT_KEY_OVERRIDES` if the registry declares it.
234
+ * Absent means "the default derivation covers everything", which today is
235
+ * almost true: exactly one row deviates.
236
+ *
237
+ * @param {string} text
238
+ * @returns {Map<string, string>}
239
+ */
240
+ function parseReportKeyOverrides(text) {
241
+ const lines = text.split('\n');
242
+ // `export` is optional: the shell side marks the array exported so shellcheck
243
+ // accepts it, but a registry without that prefix must still parse. Anchoring on
244
+ // the bare assignment is what let the `export` keyword silently DISABLE this
245
+ // override during this sprint -- the set came back EMPTY and `code-quality`
246
+ // would have emitted the wrong report key with no error anywhere.
247
+ const start = lines.findIndex((line) => /^(?:export\s+)?GATE_REPORT_KEY_OVERRIDES=\($/.test(line.trim()));
248
+ if (start === -1) return new Map(EMPTY_OVERRIDES);
249
+
250
+ const overrides = new Map();
251
+ for (let i = start + 1; i < lines.length; i++) {
252
+ const line = lines[i].trim();
253
+ if (line === ')') break;
254
+ if (line === '' || line.startsWith('#')) continue;
255
+ const match = line.match(/^"([^"|]+)\|([^"|]+)"$/);
256
+ if (!match) throw new Error(`gate-identity: unparseable GATE_REPORT_KEY_OVERRIDES row: ${line}`);
257
+ overrides.set(match[1], match[2]);
258
+ }
259
+ return overrides;
260
+ }
261
+
262
+ /**
263
+ * The artifact report key for a row.
264
+ *
265
+ * Override is applied HERE, at emission time, and never inside a comparison:
266
+ * an override that voted on equality would mask a real registry/artifact
267
+ * mismatch — the original inversion wearing a different hat (design V11).
268
+ *
269
+ * @param {{name: string, number: string}} row
270
+ * @param {Map<string, string>} [overrides]
271
+ * @returns {string}
272
+ */
273
+ function reportKey(row, overrides = EMPTY_OVERRIDES) {
274
+ const override = overrides.get(row.name);
275
+ if (override) return override;
276
+ return `gate${row.number}_${row.name.replace(/-/g, '_')}`;
277
+ }
278
+
279
+ /**
280
+ * Build gate-coverage's table from registry rows — replacing the literal array
281
+ * that carried the inversion.
282
+ *
283
+ * @param {Array<object>} rows
284
+ * @param {Map<string, string>} [overrides]
285
+ */
286
+ function deriveGateTable(rows, overrides = EMPTY_OVERRIDES) {
287
+ return rows.map((row) => ({
288
+ // `gate` is numeric for pre-commit gates (0..13) — existing consumers
289
+ // compare it with numbers (`r.gate === 0`, `row.gate === BOY_SCOUT_GATE`).
290
+ // Pre-push numbers are strings (M, M2, ML, UI, MW, S) and stay strings:
291
+ // NaN is not a number anyone can reason about, and `parseInt('M2')` would
292
+ // silently become NaN and match nothing.
293
+ gate: /^\d+$/.test(row.number) ? Number(row.number) : row.number,
294
+ number: row.number,
295
+ name: row.name,
296
+ slug: row.name,
297
+ impl: row.impl,
298
+ blocks: row.blocks === 'YES',
299
+ hook: row.hook,
300
+ reportKey: reportKey(row, overrides),
301
+ }));
302
+ }
303
+
304
+ /**
305
+ * Compare surfaces against the registry. PURE — the caller injects them.
306
+ *
307
+ * Injection is what makes AC-GATEID-002-04 checkable: a test feeds a row array
308
+ * where gate 9's name has been flipped to `sast` and asserts a violation comes
309
+ * back. Mutating the real registry file inside a test would pollute the worktree
310
+ * and could not run under parallel CI.
311
+ *
312
+ * Comparison is on the registry SLUG and NUMBER. Report keys are deliberately
313
+ * not compared, because that is where the one legitimate historical override
314
+ * lives and an override must never excuse a mismatch.
315
+ *
316
+ * @param {Array<object>} registryRows
317
+ * @param {Object<string, Map<string, string>>} surfaces hook/name -> (number -> name)
318
+ * @returns {Array<{number: string, surface: string, expected: string, actual: string}>}
319
+ */
320
+ function checkCrossSurface(registryRows, surfaces = {}) {
321
+ const violations = [];
322
+ for (const [surfaceName, byNumber] of Object.entries(surfaces)) {
323
+ if (!byNumber || typeof byNumber.get !== 'function') continue;
324
+ for (const row of registryRows) {
325
+ const actual = byNumber.get(row.number);
326
+ if (actual === undefined) {
327
+ violations.push({ number: row.number, surface: surfaceName, expected: row.name, actual: '<missing>' });
328
+ continue;
329
+ }
330
+ if (actual !== row.name) {
331
+ violations.push({ number: row.number, surface: surfaceName, expected: row.name, actual });
332
+ }
333
+ }
334
+ }
335
+ return violations;
336
+ }
337
+
338
+ module.exports = {
339
+ REGISTRY_FILENAME,
340
+ HOOKS_OF_RECORD,
341
+ EMPTY_OVERRIDES,
342
+ discoverRegistryCopies,
343
+ loadRegistry,
344
+ parseRegistry,
345
+ parseReportKeyOverrides,
346
+ reportKey,
347
+ deriveGateTable,
348
+ checkCrossSurface,
349
+ };