@boyingliu01/xp-gate 0.38.126 → 0.39.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 (291) hide show
  1. package/README.md +93 -0
  2. package/adapters/gate-3.sh +13 -2
  3. package/adapters/python.sh +36 -38
  4. package/bin/xp-gate.js +11 -0
  5. package/build-integrity/gate-10-lines.ts +98 -0
  6. package/build-integrity/gate-10.ts +98 -109
  7. package/build-integrity/quote-masker.ts +17 -3
  8. package/gate-3.sh +13 -2
  9. package/gates/common-process.ts +116 -34
  10. package/gates/common.ts +51 -15
  11. package/gates/gate-3.ts +166 -61
  12. package/gates/gate-8.ts +76 -24
  13. package/gates/gate-9.ts +276 -82
  14. package/gates/pbt-detect.ts +70 -39
  15. package/gates/python-health.ts +236 -98
  16. package/gates/test-layers.ts +103 -30
  17. package/hooks/gate-3.sh +13 -2
  18. package/hooks/gate-entries/gate-1-entry.sh +10 -1
  19. package/hooks/gate-entries/gate-5-entry.sh +5 -1
  20. package/hooks/lib/validate-code-walkthrough.cjs +324 -99
  21. package/hooks/pre-commit +52 -0
  22. package/hooks/pre-push +54 -3
  23. package/lib/agent-runtime-journal.js +104 -37
  24. package/lib/arch.js +6 -0
  25. package/lib/baseline.js +329 -201
  26. package/lib/check.js +38 -2
  27. package/lib/doctor-constants.js +43 -0
  28. package/lib/doctor.js +2008 -1001
  29. package/lib/flaky.js +178 -79
  30. package/lib/gate-runner.js +110 -63
  31. package/lib/init.js +6 -0
  32. package/lib/language-capability-surfaces.js +5 -2
  33. package/lib/language-registry.js +608 -0
  34. package/lib/language-tools.js +487 -1018
  35. package/lib/phase-transition.js +646 -446
  36. package/lib/prepush-evidence.js +174 -0
  37. package/lib/sprint-audit.js +52 -22
  38. package/lib/sprint-discovery.js +66 -35
  39. package/lib/sprint-format.js +114 -0
  40. package/lib/sprint-init.js +372 -118
  41. package/lib/sprint-status.js +134 -90
  42. package/lib/star-notice.js +346 -0
  43. package/lib/tool-display.js +52 -0
  44. package/lib/tool-install.js +179 -0
  45. package/lib/uninstall.js +331 -188
  46. package/mock-policy/gate-m3.ts +74 -23
  47. package/mock-policy/mock-decision-engine.ts +21 -7
  48. package/mock-policy/scope-scanner.ts +128 -69
  49. package/mutation/detect-ai-test.ts +20 -12
  50. package/mutation/gate-m.ts +6 -2
  51. package/mutation/init-baseline.ts +49 -13
  52. package/mutation/runners/go-mutant-runner.ts +7 -49
  53. package/mutation/runners/gremlins-runner.ts +53 -18
  54. package/mutation/runners/mutmut-runner.ts +455 -163
  55. package/mutation/runners/pitest-runner.ts +85 -131
  56. package/mutation/runners/spawn-with-capture.ts +304 -0
  57. package/mutation/runners/stryker-runner.ts +14 -55
  58. package/mutation/update-baseline.ts +25 -18
  59. package/package.json +20 -8
  60. package/plugins/claude-code/.claude-plugin/plugin.json +1 -1
  61. package/plugins/claude-code/bin/delphi-review-guard.sh +12 -61
  62. package/plugins/claude-code/skills/delphi-review/.delphi-config.json.example +6 -11
  63. package/plugins/claude-code/skills/delphi-review/AGENTS.md +1 -1
  64. package/plugins/claude-code/skills/sprint-flow/AGENTS.md +1 -1
  65. package/plugins/claude-code/skills/test-specification-alignment/AGENTS.md +1 -1
  66. package/plugins/dsh/package.json +1 -1
  67. package/plugins/dsh/scripts/prepack.cjs +43 -18
  68. package/plugins/dsh/scripts/verify-skill-provider.mjs +39 -14
  69. package/plugins/dsh/skills/delphi-review/.delphi-config.json.example +6 -11
  70. package/plugins/dsh/skills/delphi-review/AGENTS.md +1 -1
  71. package/plugins/dsh/skills/sprint-flow/AGENTS.md +1 -1
  72. package/plugins/dsh/skills/test-specification-alignment/AGENTS.md +1 -1
  73. package/plugins/opencode/index.ts +337 -123
  74. package/plugins/opencode/package.json +1 -1
  75. package/plugins/opencode/scripts/prepack.cjs +41 -16
  76. package/plugins/opencode/skills/delphi-review/.delphi-config.json.example +6 -11
  77. package/plugins/opencode/skills/delphi-review/AGENTS.md +1 -1
  78. package/plugins/opencode/skills/sprint-flow/AGENTS.md +1 -1
  79. package/plugins/opencode/skills/test-specification-alignment/AGENTS.md +1 -1
  80. package/plugins/qoder/bin/sprint-flow-guard.sh +12 -60
  81. package/plugins/qoder/plugin.json +1 -1
  82. package/plugins/qoder/skills/delphi-review/.delphi-config.json.example +6 -11
  83. package/plugins/qoder/skills/delphi-review/AGENTS.md +1 -1
  84. package/plugins/qoder/skills/sprint-flow/AGENTS.md +1 -1
  85. package/plugins/qoder/skills/test-specification-alignment/AGENTS.md +1 -1
  86. package/plugins/shared/README.md +3 -0
  87. package/plugins/shared/bin/delphi-review-guard.sh +68 -0
  88. package/principles/adapters/control-nesting.ts +481 -168
  89. package/principles/adapters/cpp.ts +61 -22
  90. package/principles/adapters/csharp.ts +183 -66
  91. package/principles/adapters/dart.ts +11 -1
  92. package/principles/adapters/duplication.ts +49 -16
  93. package/principles/adapters/import-clause.ts +62 -15
  94. package/principles/adapters/java.ts +199 -70
  95. package/principles/adapters/line-comment.ts +18 -0
  96. package/principles/adapters/member-scan.ts +50 -8
  97. package/principles/adapters/php.ts +232 -103
  98. package/principles/adapters/python.ts +25 -18
  99. package/principles/adapters/quote-state.ts +21 -8
  100. package/principles/adapters/typescript-mask.ts +276 -0
  101. package/principles/adapters/typescript.ts +206 -200
  102. package/principles/analyzer.ts +16 -6
  103. package/principles/baseline-prune.ts +18 -8
  104. package/principles/baseline.ts +28 -11
  105. package/principles/boy-scout-usage.ts +26 -0
  106. package/principles/boy-scout.ts +261 -180
  107. package/principles/config.ts +183 -57
  108. package/principles/direct-execution.ts +24 -12
  109. package/principles/lint-baseline.ts +235 -122
  110. package/principles/rules/arch/dependency.ts +34 -25
  111. package/principles/rules/arch/shared.ts +24 -20
  112. package/principles/rules/clean-code/deep-nesting.ts +23 -13
  113. package/principles/rules/clean-code/god-class.ts +67 -41
  114. package/principles/rules/clean-code/large-file.ts +30 -23
  115. package/principles/rules/clean-code/long-function.ts +51 -37
  116. package/principles/rules/clean-code/magic-numbers.ts +51 -36
  117. package/principles/rules/clean-code/many-exports.ts +46 -29
  118. package/principles/rules/clean-code/missing-error-handling.ts +38 -20
  119. package/principles/rules/clean-code/too-many-params.ts +41 -22
  120. package/principles/rules/function-source.ts +62 -0
  121. package/principles/rules/solid/dip.ts +10 -6
  122. package/principles/rules/solid/isp.ts +64 -24
  123. package/principles/rules/solid/lsp.ts +66 -18
  124. package/principles/rules/solid/ocp.ts +29 -13
  125. package/principles/rules/solid/srp.ts +34 -18
  126. package/principles/warnings-count.ts +43 -0
  127. package/scripts/__tests__/prepush-source-classification.test.js +129 -0
  128. package/scripts/delphi-config-read.cjs +245 -0
  129. package/scripts/delphi-external-review.cjs +410 -585
  130. package/scripts/delphi-json-extract.cjs +108 -0
  131. package/scripts/delphi-model-validation.cjs +297 -0
  132. package/scripts/delphi-prompts.cjs +55 -0
  133. package/scripts/delphi-repo-tools.cjs +273 -0
  134. package/scripts/delphi-seat-calibration.cjs +204 -0
  135. package/scripts/run-bats-ci.cjs +240 -97
  136. package/scripts/sync-package-content.js +18 -2
  137. package/skills/delphi-review/.delphi-config.json.example +6 -11
  138. package/skills/delphi-review/AGENTS.md +1 -1
  139. package/skills/sprint-flow/AGENTS.md +1 -1
  140. package/skills/test-specification-alignment/AGENTS.md +1 -1
  141. package/lib/__tests__/agent-runtime-journal.test.js +0 -326
  142. package/lib/__tests__/arch-config-template.test.js +0 -190
  143. package/lib/__tests__/arch.test.js +0 -430
  144. package/lib/__tests__/assertion-debt.test.js +0 -99
  145. package/lib/__tests__/audit-cli-contract.test.ts +0 -117
  146. package/lib/__tests__/audit-log.test.ts +0 -107
  147. package/lib/__tests__/audit-skip-reasons.test.ts +0 -143
  148. package/lib/__tests__/baseline-completeness.test.js +0 -264
  149. package/lib/__tests__/baseline-shell-scope.test.js +0 -60
  150. package/lib/__tests__/baseline-unevaluated.test.js +0 -142
  151. package/lib/__tests__/baseline.test.js +0 -212
  152. package/lib/__tests__/bootstrap.test.js +0 -60
  153. package/lib/__tests__/check-alignment-cli.test.mjs +0 -94
  154. package/lib/__tests__/check-alignment-reasons.test.mjs +0 -101
  155. package/lib/__tests__/check-all-skip-accounting.test.js +0 -171
  156. package/lib/__tests__/check-changed-brief.test.js +0 -63
  157. package/lib/__tests__/check-normalize-exit.test.js +0 -24
  158. package/lib/__tests__/check-single-file.test.js +0 -114
  159. package/lib/__tests__/check-tools-list.test.js +0 -155
  160. package/lib/__tests__/check-version.test.js +0 -463
  161. package/lib/__tests__/coverage-scope.test.js +0 -140
  162. package/lib/__tests__/coverage-threshold.test.js +0 -80
  163. package/lib/__tests__/crap-cli.test.js +0 -87
  164. package/lib/__tests__/crap.test.js +0 -494
  165. package/lib/__tests__/debt-classify.test.js +0 -78
  166. package/lib/__tests__/delphi-channel-doctor.test.js +0 -116
  167. package/lib/__tests__/delphi-channel-uninstall.test.js +0 -128
  168. package/lib/__tests__/delphi-channel.test.js +0 -109
  169. package/lib/__tests__/delphi-setup.test.js +0 -203
  170. package/lib/__tests__/deploy-manifest-check-wired.test.js +0 -138
  171. package/lib/__tests__/deploy-manifest-completeness.test.js +0 -151
  172. package/lib/__tests__/deploy-manifest-consumers-adapter-uninstall.test.js +0 -40
  173. package/lib/__tests__/deploy-manifest-consumers-no-private-lists.test.js +0 -74
  174. package/lib/__tests__/deploy-manifest-projection.test.js +0 -66
  175. package/lib/__tests__/deploy-manifest-shell-parity.test.js +0 -108
  176. package/lib/__tests__/deploy-manifest.test.js +0 -97
  177. package/lib/__tests__/detect-deps-dsh-profile.test.js +0 -323
  178. package/lib/__tests__/detect-deps-gate-identity.test.js +0 -135
  179. package/lib/__tests__/detect-deps.test.js +0 -655
  180. package/lib/__tests__/doctor-469-hook-env.test.js +0 -211
  181. package/lib/__tests__/doctor-arch-tools.test.js +0 -169
  182. package/lib/__tests__/doctor-audit-ledger.test.js +0 -61
  183. package/lib/__tests__/doctor-brief.test.js +0 -59
  184. package/lib/__tests__/doctor-delphi.test.js +0 -628
  185. package/lib/__tests__/doctor-drift-direction.test.js +0 -104
  186. package/lib/__tests__/doctor-drift-round2.test.js +0 -215
  187. package/lib/__tests__/doctor-exec-retry.test.js +0 -162
  188. package/lib/__tests__/doctor-executed-surface.test.js +0 -230
  189. package/lib/__tests__/doctor-helpers.test.js +0 -139
  190. package/lib/__tests__/doctor-hook-drift.test.js +0 -329
  191. package/lib/__tests__/doctor-hook-signatures.test.js +0 -65
  192. package/lib/__tests__/doctor-machine-mutation.test.js +0 -116
  193. package/lib/__tests__/doctor-module-drift.test.js +0 -212
  194. package/lib/__tests__/doctor-module-resolution-parity.test.js +0 -463
  195. package/lib/__tests__/doctor-path-equivalence.test.js +0 -70
  196. package/lib/__tests__/doctor-repair-boundary.test.js +0 -52
  197. package/lib/__tests__/doctor-signature-stability.test.js +0 -55
  198. package/lib/__tests__/doctor-spawn-capability.test.js +0 -116
  199. package/lib/__tests__/doctor-timeout-partial.test.js +0 -79
  200. package/lib/__tests__/doctor-tool-delegation.test.js +0 -156
  201. package/lib/__tests__/doctor-tui-skill-freshness.test.js +0 -385
  202. package/lib/__tests__/doctor.test.js +0 -1320
  203. package/lib/__tests__/find-bash-wsl.test.js +0 -121
  204. package/lib/__tests__/flaky.test.js +0 -128
  205. package/lib/__tests__/foreign-hooks-global.test.js +0 -125
  206. package/lib/__tests__/gate-audit-skip.test.ts +0 -81
  207. package/lib/__tests__/gate-audit.test.ts +0 -440
  208. package/lib/__tests__/gate-coverage-hook-floor.test.js +0 -94
  209. package/lib/__tests__/gate-coverage.test.js +0 -204
  210. package/lib/__tests__/gate-entry-provenance.test.js +0 -71
  211. package/lib/__tests__/gate-numbering.test.js +0 -79
  212. package/lib/__tests__/gate-rules.test.js +0 -58
  213. package/lib/__tests__/gate-runner-tsx-invocation.test.js +0 -149
  214. package/lib/__tests__/gate-runner-verdict.test.js +0 -105
  215. package/lib/__tests__/gate-runner.test.js +0 -371
  216. package/lib/__tests__/gate2-verdict.test.js +0 -183
  217. package/lib/__tests__/helpers/lib-sandbox.cjs +0 -55
  218. package/lib/__tests__/hook-health-path.test.js +0 -109
  219. package/lib/__tests__/hook-health.test.js +0 -85
  220. package/lib/__tests__/init-gitignore.test.js +0 -204
  221. package/lib/__tests__/init-gitleaks-notice.test.js +0 -57
  222. package/lib/__tests__/init.test.js +0 -530
  223. package/lib/__tests__/install-cmd.test.js +0 -6
  224. package/lib/__tests__/install-sh-deploy-manifest.test.js +0 -80
  225. package/lib/__tests__/install-skill-full-dir.test.js +0 -194
  226. package/lib/__tests__/install-skill.test.js +0 -416
  227. package/lib/__tests__/install-tools-repair.test.js +0 -263
  228. package/lib/__tests__/issue-519-phase-transition-guard.test.js +0 -233
  229. package/lib/__tests__/issue-566-sync-hooks-backup.test.js +0 -228
  230. package/lib/__tests__/issue-583-hook-deploy-log.test.js +0 -121
  231. package/lib/__tests__/issue-586-principles-cmdline.test.js +0 -218
  232. package/lib/__tests__/issue-589-check-all-gate3.test.js +0 -190
  233. package/lib/__tests__/issue-590-archlint-vacuous-pass.test.js +0 -138
  234. package/lib/__tests__/issue-618-gate-not-run.test.js +0 -100
  235. package/lib/__tests__/jscpd-entry-resolution.test.js +0 -143
  236. package/lib/__tests__/language-capability.test.js +0 -318
  237. package/lib/__tests__/language-tools-build-file-install.test.js +0 -82
  238. package/lib/__tests__/language-tools-detect.test.js +0 -301
  239. package/lib/__tests__/migrate.test.js +0 -232
  240. package/lib/__tests__/mirror-manifest.test.js +0 -64
  241. package/lib/__tests__/mirror-sync.test.js +0 -803
  242. package/lib/__tests__/next-sprint.test.js +0 -231
  243. package/lib/__tests__/npm-package.test.js +0 -140
  244. package/lib/__tests__/phase-transition.test.js +0 -1136
  245. package/lib/__tests__/principles-csharp-coverage.test.js +0 -227
  246. package/lib/__tests__/principles-directory.test.js +0 -87
  247. package/lib/__tests__/qoder-delphi-agents.test.js +0 -316
  248. package/lib/__tests__/retro-gate-m.test.js +0 -144
  249. package/lib/__tests__/retro.test.js +0 -131
  250. package/lib/__tests__/rework.test.js +0 -127
  251. package/lib/__tests__/rollback.test.js +0 -183
  252. package/lib/__tests__/runtime-journal.test.js +0 -164
  253. package/lib/__tests__/sastd-client.test.js +0 -514
  254. package/lib/__tests__/shared-paths-lazy-home.test.js +0 -67
  255. package/lib/__tests__/shared-paths.test.js +0 -130
  256. package/lib/__tests__/shared-utils-copyHooks-manifest.test.js +0 -69
  257. package/lib/__tests__/shared-utils.test.js +0 -180
  258. package/lib/__tests__/skill-flags.test.js +0 -48
  259. package/lib/__tests__/slo.test.js +0 -89
  260. package/lib/__tests__/sprint-audit.test.js +0 -207
  261. package/lib/__tests__/sprint-discovery.test.ts +0 -366
  262. package/lib/__tests__/sprint-state-manager.test.js +0 -310
  263. package/lib/__tests__/sprint-status-rework-704.test.js +0 -149
  264. package/lib/__tests__/sprint-status-rework.test.js +0 -329
  265. package/lib/__tests__/sprint-status.test.js +0 -193
  266. package/lib/__tests__/sprint-status.test.ts +0 -213
  267. package/lib/__tests__/test-alignment-java-702.test.ts +0 -177
  268. package/lib/__tests__/test-alignment-range-guard.test.ts +0 -82
  269. package/lib/__tests__/test-alignment.test.ts +0 -853
  270. package/lib/__tests__/tool-audit-collect.test.js +0 -184
  271. package/lib/__tests__/tool-audit-fixtures.js +0 -87
  272. package/lib/__tests__/tool-audit-latest.test.js +0 -84
  273. package/lib/__tests__/tool-audit.test.js +0 -428
  274. package/lib/__tests__/tsconfig.json +0 -8
  275. package/lib/__tests__/tsx-resolution.test.js +0 -89
  276. package/lib/__tests__/ui-detector.test.ts +0 -459
  277. package/lib/__tests__/ui-review.test.ts +0 -132
  278. package/lib/__tests__/uninstall-global-residue.test.js +0 -545
  279. package/lib/__tests__/uninstall-skill.test.js +0 -189
  280. package/lib/__tests__/uninstall.test.js +0 -717
  281. package/lib/__tests__/update-hooks.test.js +0 -737
  282. package/lib/__tests__/update-skill-flags.test.js +0 -78
  283. package/lib/__tests__/update-skill.test.js +0 -644
  284. package/lib/__tests__/upgrade-exec.test.js +0 -273
  285. package/lib/__tests__/upgrade-skill-sync.test.js +0 -65
  286. package/lib/__tests__/upgrade.test.js +0 -78
  287. package/lib/__tests__/windows-bash-probe.test.js +0 -123
  288. package/lib/check-alignment-runner.cjs +0 -97
  289. package/lib/coverage-total.sh +0 -92
  290. package/lib/layer-baseline.cjs +0 -94
  291. package/lib/mattpocock-license-verdict.json +0 -7
package/lib/uninstall.js CHANGED
@@ -129,8 +129,18 @@ function getConfig() {
129
129
  }
130
130
  }
131
131
 
132
+ /**
133
+ * Persist the config, or throw with the path.
134
+ *
135
+ * Uninstall edits this file to drop what it removed; a silent failure would leave the
136
+ * config pointing at things that no longer exist.
137
+ */
132
138
  function saveConfig(config) {
133
- fs.writeFileSync(CONFIG_FILE, JSON.stringify(config, null, 2));
139
+ try {
140
+ fs.writeFileSync(CONFIG_FILE, JSON.stringify(config, null, 2));
141
+ } catch (err) {
142
+ throw new Error(`cannot save config to ${CONFIG_FILE}: ${err.message}`);
143
+ }
134
144
  }
135
145
 
136
146
  function getGitDir() {
@@ -249,9 +259,20 @@ function isDirEmpty(dir) {
249
259
  }
250
260
  }
251
261
 
262
+ /**
263
+ * Copy a directory tree.
264
+ *
265
+ * An unreadable source aborts with the path named: a partial backup is worse than
266
+ * none, because it looks like a backup.
267
+ */
252
268
  function copyDirSync(src, dest) {
253
- fs.mkdirSync(dest, { recursive: true });
254
- const entries = fs.readdirSync(src, { withFileTypes: true });
269
+ let entries;
270
+ try {
271
+ fs.mkdirSync(dest, { recursive: true });
272
+ entries = fs.readdirSync(src, { withFileTypes: true });
273
+ } catch (err) {
274
+ throw new Error(`cannot copy ${src} to ${dest}: ${err.message}`);
275
+ }
255
276
  for (const entry of entries) {
256
277
  const srcPath = path.join(src, entry.name);
257
278
  const destPath = path.join(dest, entry.name);
@@ -285,84 +306,116 @@ function cleanupBackup(backupMeta) {
285
306
  * Build the uninstall plan based on mode.
286
307
  * Returns an array of operation objects: { type, path, signature, label, critical }
287
308
  */
288
- function buildPlan(mode) {
289
- const plan = [];
290
- const manifest = getConfig() && getConfig().manifest ? getConfig().manifest : null;
309
+ /**
310
+ * Append the project-local uninstall entries to `plan`.
311
+ *
312
+ * Split out of `buildPlan`, which measured CCN 17 over 158 lines by holding
313
+ * both modes. `plan` is passed in rather than returned so the two halves
314
+ * compose without either owning the list, and the shared template entry stays
315
+ * in `buildPlan` where it belongs to neither.
316
+ *
317
+ * @param {Array<object>} plan
318
+ * @param {object|null} manifest
319
+ */
320
+ /**
321
+ * Plan the five entries every local install creates.
322
+ *
323
+ * All fully owned (signature checked) and all `critical`: these are the files that
324
+ * make the gates run, so uninstalling must not leave one behind.
325
+ */
326
+ function pushHookEntries(plan, hooksDir, githooksDir) {
327
+ const owned = (base, name, manifestKey) => plan.push({
328
+ type: 'file',
329
+ path: path.join(base, name),
330
+ signature: SIGNATURES[name],
331
+ label: manifestKey,
332
+ manifestKey,
333
+ critical: true,
334
+ });
335
+
336
+ owned(hooksDir, 'pre-commit', '.git/hooks/pre-commit');
337
+ owned(hooksDir, 'pre-push', '.git/hooks/pre-push');
338
+ owned(hooksDir, 'post-merge', '.git/hooks/post-merge');
339
+ owned(githooksDir, 'adapter-common.sh', 'githooks/adapter-common.sh');
340
+
341
+ const adaptersDir = path.join(githooksDir, 'adapters');
342
+ if (fs.existsSync(adaptersDir)) {
343
+ plan.push({ type: 'dir', path: adaptersDir, label: 'githooks/adapters/', critical: true });
344
+ }
345
+ }
291
346
 
292
- if (mode === 'local') {
347
+ /**
348
+ * Plan the project-level config files `init` generates.
349
+ *
350
+ * Matched by a content SIGNATURE rather than by ownership, and non-critical: a
351
+ * project that edited its own baseline keeps it.
352
+ */
353
+ function pushProjectConfigEntries(plan, projectRoot) {
354
+ const files = [
355
+ { name: '.xp-gate-config.json', signature: '"languages"' },
356
+ { name: '.warnings-baseline.json', signature: '"warnings"' },
357
+ ];
358
+ for (const { name, signature } of files) {
359
+ const target = path.join(projectRoot, name);
360
+ if (!fs.existsSync(target)) continue;
361
+ plan.push({ type: 'file', path: target, signature, label: name, critical: false });
362
+ }
363
+ }
364
+
365
+ function buildLocalPlanInto(plan, manifest) {
293
366
  const gitDir = getGitDir();
294
367
  if (gitDir) {
295
368
  const projectRoot = path.dirname(gitDir);
296
369
  const hooksDir = path.join(projectRoot, '.git', 'hooks');
297
370
  const githooksDir = path.join(projectRoot, 'githooks');
298
371
 
299
- plan.push({
300
- type: 'file',
301
- path: path.join(hooksDir, 'pre-commit'),
302
- signature: SIGNATURES['pre-commit'],
303
- label: '.git/hooks/pre-commit',
304
- manifestKey: '.git/hooks/pre-commit',
305
- critical: true
306
- });
307
- plan.push({
308
- type: 'file',
309
- path: path.join(hooksDir, 'pre-push'),
310
- signature: SIGNATURES['pre-push'],
311
- label: '.git/hooks/pre-push',
312
- manifestKey: '.git/hooks/pre-push',
313
- critical: true
314
- });
315
- plan.push({
316
- type: 'file',
317
- path: path.join(hooksDir, 'post-merge'),
318
- signature: SIGNATURES['post-merge'],
319
- label: '.git/hooks/post-merge',
320
- manifestKey: '.git/hooks/post-merge',
321
- critical: true
322
- });
323
- plan.push({
324
- type: 'file',
325
- path: path.join(githooksDir, 'adapter-common.sh'),
326
- signature: SIGNATURES['adapter-common.sh'],
327
- label: 'githooks/adapter-common.sh',
328
- manifestKey: 'githooks/adapter-common.sh',
329
- critical: true
330
- });
331
- const adaptersDir = path.join(githooksDir, 'adapters');
332
- if (fs.existsSync(adaptersDir)) {
333
- plan.push({
334
- type: 'dir',
335
- path: adaptersDir,
336
- label: 'githooks/adapters/',
337
- critical: true
338
- });
339
- }
372
+ pushHookEntries(plan, hooksDir, githooksDir);
373
+ pushProjectConfigEntries(plan, projectRoot);
374
+ }
375
+ }
340
376
 
341
- // Project-level config files (generated by init)
342
- const langConfig = path.join(projectRoot, '.xp-gate-config.json');
343
- if (fs.existsSync(langConfig)) {
344
- plan.push({
345
- type: 'file',
346
- path: langConfig,
347
- signature: '"languages"',
348
- label: '.xp-gate-config.json',
349
- critical: false
350
- });
351
- }
352
- const baselineFile = path.join(projectRoot, '.warnings-baseline.json');
353
- if (fs.existsSync(baselineFile)) {
354
- plan.push({
355
- type: 'file',
356
- path: baselineFile,
357
- signature: '"warnings"',
358
- label: '.warnings-baseline.json',
359
- critical: false
360
- });
361
- }
377
+ /**
378
+ * Append the global uninstall entries to `plan`.
379
+ *
380
+ * @param {Array<object>} plan
381
+ * @param {object|null} manifest
382
+ */
383
+ /**
384
+ * Plan the files `setup-global` writes outside the hook/config entries.
385
+ *
386
+ * #663: setup-global also writes `modules/`, a `node_modules/` tree, `package.json`,
387
+ * `package-lock.json` and the `xp-gate.json` manifest. None were in the plan, so
388
+ * uninstall printed "Uninstall complete" over an installation still ~1000 files on
389
+ * disk. The residue is not cosmetic: a leftover `node_modules/` makes the NEXT
390
+ * setup-global skip its own install and reuse a stale dependency tree, and a leftover
391
+ * `xp-gate.json` carries the previous manifest into `doctor`, which reports it as the
392
+ * current installation.
393
+ */
394
+ function planGlobalInstallResidue(plan) {
395
+ for (const item of GLOBAL_INSTALL_RESIDUE) {
396
+ const target = path.join(CONFIG_DIR, item.key);
397
+ // One stat, not exists-then-stat: the pair has a window in which the entry can
398
+ // vanish and the second call throws.
399
+ let isDir;
400
+ try {
401
+ isDir = fs.statSync(target).isDirectory();
402
+ } catch {
403
+ continue; // absent or unreadable: nothing to plan
362
404
  }
405
+ plan.push({
406
+ type: isDir ? 'dir' : 'file',
407
+ path: target,
408
+ label: item.label,
409
+ critical: false,
410
+ // #714: a fixed-path file we install ourselves needs no content signature.
411
+ // Carrying the flag through the plan is what makes the delete happen instead
412
+ // of stopping at "does not contain xp-gate signature".
413
+ ownedByPath: item.ownedByPath === true,
414
+ });
363
415
  }
416
+ }
364
417
 
365
- if (mode === 'global') {
418
+ function buildGlobalPlanInto(plan, manifest) {
366
419
  plan.push({
367
420
  type: 'gitconfig',
368
421
  action: 'unset-hooks-path',
@@ -387,38 +440,13 @@ function buildPlan(mode) {
387
440
  });
388
441
  }
389
442
 
390
- // #663: `setup-global` also writes modules/, a node_modules/ tree, a
391
- // package.json + package-lock.json and the xp-gate.json manifest. None of them
392
- // were in the plan, so uninstall printed "Uninstall complete" over an
393
- // installation that was still ~1000 files on disk. The residue is not
394
- // cosmetic: a leftover node_modules/ makes the NEXT setup-global skip its own
395
- // install and reuse a stale dependency tree, and a leftover xp-gate.json
396
- // carries the previous version's manifest/lastInit into `doctor`, which then
397
- // reports it as the current installation.
398
- const configDir = CONFIG_DIR;
399
- for (const item of GLOBAL_INSTALL_RESIDUE) {
400
- const target = path.join(configDir, item.key);
401
- if (fs.existsSync(target)) {
402
- const isDir = fs.statSync(target).isDirectory();
403
- plan.push({
404
- type: isDir ? 'dir' : 'file',
405
- path: target,
406
- label: `~/.config/xp-gate/${item.label}`,
407
- critical: false,
408
- // #714: a fixed-path file we install ourselves needs no content
409
- // signature. Carrying the flag through the plan is what makes the
410
- // delete actually happen instead of stopping at "does not contain
411
- // xp-gate signature".
412
- ownedByPath: item.ownedByPath === true
413
- });
414
- }
415
- }
443
+ planGlobalInstallResidue(plan);
416
444
 
417
445
  // User data is deliberately NOT deleted. Reporting it is the second half of
418
446
  // the fix: leaving it behind silently is how a user ends up with a stray
419
447
  // config they cannot attribute.
420
448
  for (const item of GLOBAL_USER_DATA) {
421
- const target = path.join(configDir, item.key);
449
+ const target = path.join(CONFIG_DIR, item.key);
422
450
  if (fs.existsSync(target)) {
423
451
  plan.push({
424
452
  type: 'retain',
@@ -429,6 +457,16 @@ function buildPlan(mode) {
429
457
  });
430
458
  }
431
459
  }
460
+ }
461
+
462
+ function buildPlan(mode) {
463
+ const config = getConfig();
464
+ const manifest = config && config.manifest ? config.manifest : null;
465
+ const plan = [];
466
+ if (mode === 'local') {
467
+ buildLocalPlanInto(plan, manifest);
468
+ } else if (mode === 'global') {
469
+ buildGlobalPlanInto(plan, manifest);
432
470
  }
433
471
 
434
472
  // Template dir is common to both modes
@@ -458,7 +496,14 @@ function removeFile(item, config) {
458
496
  // stayed.
459
497
  if (item.ownedByPath === true) {
460
498
  if (!fs.existsSync(item.path)) return false;
461
- fs.unlinkSync(item.path);
499
+ try {
500
+ fs.unlinkSync(item.path);
501
+ } catch (err) {
502
+ // Report a failure AS a failure: printing "Removed" for a file still on disk
503
+ // is the residue problem this command exists to end.
504
+ console.error(` ✗ Could not remove ${item.label}: ${err.message}`);
505
+ return false;
506
+ }
462
507
  console.log(` Removed ${item.label}`);
463
508
  return true;
464
509
  }
@@ -568,75 +613,25 @@ function executePlanItem(item, config) {
568
613
  * @param {string[]} args CLI arguments
569
614
  * @returns {number} exit code (0 = success, 1 = error)
570
615
  */
571
- async function uninstall(args) {
572
- const options = {
573
- dryRun: args.includes('--dry-run'),
574
- force: args.includes('--force'),
575
- forceLocal: args.includes('--local'),
576
- forceGlobal: args.includes('--global'),
577
- purge: args.includes('--purge'),
578
- };
579
-
580
- // §4.3 Step 1: Read config
581
- const config = getConfig();
582
-
583
- // §4.3 Step 1: No config → exit cleanly (AC-09 idempotency)
584
- if (!config) {
585
- console.log('No xp-gate installation found');
586
- return 0;
587
- }
588
-
589
- // §4.3 Step 1: Already uninstalled → exit cleanly (AC-09 idempotency)
590
- if (config.mode === 'uninstalled') {
591
- console.log('No xp-gate installation found');
592
- return 0;
593
- }
594
-
595
- // §4.3 Step 2: Determine mode
596
- let mode = config.mode;
597
- if (options.forceLocal) mode = 'local';
598
- if (options.forceGlobal) mode = 'global';
599
-
600
- if (mode !== 'local' && mode !== 'global') {
601
- console.log('No xp-gate installation found');
602
- return 0;
603
- }
604
-
605
- // §4.3 Step 3: Build uninstall plan
606
- const plan = buildPlan(mode);
607
-
608
- // §4.3 Step 3b: Add purge items if --purge
609
- const purgeDirs = [];
610
- if (options.purge) {
611
- const configDir = CONFIG_DIR;
612
- const xpGateDir = path.join(HOME_DIR, '.xp-gate');
613
- purgeDirs.push({ label: '~/.xp-gate/', path: xpGateDir });
614
- purgeDirs.push({ label: '~/.config/xp-gate/', path: configDir });
615
- if (mode === 'local') {
616
- const gitDir = getGitDir();
617
- if (gitDir) {
618
- const projectXpGate = path.join(path.dirname(gitDir), '.xp-gate');
619
- purgeDirs.push({ label: '.xp-gate/ (project)', path: projectXpGate });
620
- }
621
- }
622
- }
623
-
624
- if (plan.length === 0 && purgeDirs.length === 0) {
625
- console.log('Nothing to uninstall');
626
- // Still update config to uninstalled
627
- saveConfig({ ...config, mode: 'uninstalled', uninstalled: new Date().toISOString() });
628
- return 0;
629
- }
630
-
631
- // §4.3 Step 4: Print plan
616
+ /**
617
+ * Print what is about to happen, with removal and retention stated separately.
618
+ *
619
+ * #724: 'retain' entries used to be printed under "The following will be removed"
620
+ * and then kept, with no further mention anywhere in the output. A user scripting
621
+ * cleanup from this preview would delete a directory they had been told was already
622
+ * gone. The two groups are separate now, and the retained list is echoed again at the
623
+ * end of the run.
624
+ *
625
+ * @param {string} mode
626
+ * @param {Array} plan
627
+ * @param {Array} purgeDirs
628
+ * @param {{purge?: boolean}} options
629
+ * @returns {Array} the retained entries, which the caller restates at the end
630
+ */
631
+ function printUninstallPlan(mode, plan, purgeDirs, options) {
632
632
  console.log(`XP-Gate Uninstall (${mode} mode)`);
633
633
  console.log('=======================\n');
634
634
 
635
- // #724: 'retain' entries used to be printed under "The following will be
636
- // removed" and then kept, with no further mention anywhere in the output.
637
- // A user scripting cleanup from this preview would delete a directory they
638
- // had been told was gone. The two groups are now stated separately, and the
639
- // retained list is echoed again at the end.
640
635
  const removable = plan.filter((item) => item.retain !== true);
641
636
  const retained = plan.filter((item) => item.retain === true);
642
637
 
@@ -658,17 +653,55 @@ async function uninstall(args) {
658
653
  console.log(` • ${d.label}`);
659
654
  }
660
655
  }
656
+ return retained;
657
+ }
661
658
 
662
- // §4.3 Step 5: Dry-run → exit
663
- if (options.dryRun) {
664
- console.log('\nDry-run mode — no files were modified');
665
- return 0;
659
+ /**
660
+ * Run the plan: state machine, backup, removals, purge, final state write.
661
+ *
662
+ * The ORDER is the safety property. The state moves to `uninstalling` BEFORE anything
663
+ * is removed, so a crash halfway leaves a config saying "do not trust this
664
+ * installation" rather than one claiming to be active. The backup is taken before the
665
+ * destructive loop for the same reason.
666
+ *
667
+ * Errors do not stop the run: one unwritable file must not strand the rest. They are
668
+ * collected into the return value, which decides whether the backup is cleaned up.
669
+ *
670
+ * @returns {{hadErrors: boolean, backupMeta: object}} `backupMeta` is returned so the
671
+ * caller can decide whether to keep or discard the snapshot.
672
+ */
673
+ /**
674
+ * Delete the whole directories `--purge` asks for.
675
+ *
676
+ * Separate from the plan loop because these are trees removed with `force`, not
677
+ * owned files: there is no signature to check and no partial failure to report
678
+ * beyond "could not remove". A dry run prints them in the preview's shape, because
679
+ * the preview only lists what the PLAN will touch.
680
+ *
681
+ * @param {Array<{label: string, path: string}>} purgeDirs
682
+ * @param {{dryRun?: boolean}} options
683
+ * @returns {boolean} whether anything failed
684
+ */
685
+ function runPurge(purgeDirs, options) {
686
+ let failed = false;
687
+ for (const dir of purgeDirs) {
688
+ if (options.dryRun) {
689
+ console.log(` • ${dir.label}`);
690
+ continue;
691
+ }
692
+ if (!fs.existsSync(dir.path)) continue;
693
+ try {
694
+ fs.rmSync(dir.path, { recursive: true, force: true });
695
+ console.log(` Removed ${dir.label}`);
696
+ } catch (err) {
697
+ console.warn(` Warning: Could not remove ${dir.label}: ${err.message}`);
698
+ failed = true;
699
+ }
666
700
  }
701
+ return failed;
702
+ }
667
703
 
668
- // §4.3 Step 6: Confirm
669
- // Skipped in test environment since we use --force or non-interactive
670
- // In real usage with TTY, would prompt here
671
-
704
+ function executeUninstallPlan(plan, config, purgeDirs, options) {
672
705
  // §4.8 State machine: active → uninstalling
673
706
  saveConfig({ ...config, mode: 'uninstalling' });
674
707
 
@@ -687,22 +720,7 @@ async function uninstall(args) {
687
720
  }
688
721
  }
689
722
 
690
- if (options.purge) {
691
- for (const d of purgeDirs) {
692
- if (options.dryRun) {
693
- console.log(` • ${d.label}`);
694
- continue;
695
- }
696
- if (!fs.existsSync(d.path)) continue;
697
- try {
698
- fs.rmSync(d.path, { recursive: true, force: true });
699
- console.log(` Removed ${d.label}`);
700
- } catch (e) {
701
- console.warn(` Warning: Could not remove ${d.label}: ${e.message}`);
702
- hadErrors = true;
703
- }
704
- }
705
- }
723
+ const purgeErrors = options.purge ? runPurge(purgeDirs, options) : false;
706
724
 
707
725
  // §4.8 State machine: uninstalling → uninstalled
708
726
  try {
@@ -722,6 +740,131 @@ async function uninstall(args) {
722
740
  if (!hadErrors) {
723
741
  cleanupBackup(backupMeta);
724
742
  }
743
+ return { hadErrors: hadErrors || purgeErrors, backupMeta };
744
+ }
745
+
746
+ /**
747
+ * Decide the install mode and build the plan (plus purge targets).
748
+ *
749
+ * Returns `mode: null` when there is nothing xp-gate-shaped on this machine, which
750
+ * the caller reports as a clean exit -- uninstalling twice is not an error, and
751
+ * saying so twice is idempotency (#AC-09), not noise.
752
+ *
753
+ * Purge targets are scoped to the MODE: a local install has a project `.xp-gate/`
754
+ * worth removing, a global one does not, and `force` flags override the recorded
755
+ * mode so a half-broken config can still be cleaned up.
756
+ *
757
+ * @param {object} config
758
+ * @param {{forceLocal?: boolean, forceGlobal?: boolean, purge?: boolean}} options
759
+ * @returns {{mode: string|null, plan: Array, purgeDirs: Array}}
760
+ */
761
+ function prepareUninstallPlan(config, options) {
762
+ // §4.3 Step 2: Determine mode
763
+ let mode = config.mode;
764
+ if (options.forceLocal) mode = 'local';
765
+ if (options.forceGlobal) mode = 'global';
766
+
767
+ if (mode !== 'local' && mode !== 'global') {
768
+ console.log('No xp-gate installation found');
769
+ return 0;
770
+ }
771
+
772
+ // §4.3 Step 3: Build uninstall plan
773
+ const plan = buildPlan(mode);
774
+
775
+ // §4.3 Step 3b: Add purge items if --purge
776
+ const purgeDirs = [];
777
+ if (options.purge) {
778
+ const configDir = CONFIG_DIR;
779
+ const xpGateDir = path.join(HOME_DIR, '.xp-gate');
780
+ purgeDirs.push({ label: '~/.xp-gate/', path: xpGateDir });
781
+ purgeDirs.push({ label: '~/.config/xp-gate/', path: configDir });
782
+ if (mode === 'local') {
783
+ const gitDir = getGitDir();
784
+ if (gitDir) {
785
+ const projectXpGate = path.join(path.dirname(gitDir), '.xp-gate');
786
+ purgeDirs.push({ label: '.xp-gate/ (project)', path: projectXpGate });
787
+ }
788
+ }
789
+ }
790
+
791
+ return { mode, plan, purgeDirs };
792
+ }
793
+
794
+ /**
795
+ * Whether there is nothing to uninstall.
796
+ *
797
+ * Two conditions, one message: no config at all, and a config that already records
798
+ * the uninstalled state. Both are the AC-09 idempotency case -- running `uninstall`
799
+ * twice is not an error, and the second run has nothing to report beyond that.
800
+ *
801
+ * @param {object|null} config
802
+ * @returns {boolean}
803
+ */
804
+ function isAlreadyGone(config) {
805
+ if (!config || config.mode === 'uninstalled') {
806
+ console.log('No xp-gate installation found');
807
+ return true;
808
+ }
809
+ return false;
810
+ }
811
+
812
+ /**
813
+ * Record that the plan was empty.
814
+ *
815
+ * The config is still moved to `uninstalled`: the installation may consist only of
816
+ * entries the guard refused to touch, and leaving the mode `active` would make the
817
+ * next run repeat the same no-op. Saying "nothing to uninstall" is a result, not a
818
+ * failure.
819
+ *
820
+ * @param {object} config
821
+ * @returns {number} exit code
822
+ */
823
+ function recordNothingToDo(config) {
824
+ console.log('Nothing to uninstall');
825
+ saveConfig({ ...config, mode: 'uninstalled', uninstalled: new Date().toISOString() });
826
+ return 0;
827
+ }
828
+
829
+ /**
830
+ * Say that a dry run changed nothing.
831
+ *
832
+ * @returns {number} exit code
833
+ */
834
+ function reportDryRun() {
835
+ console.log('\nDry-run mode — no files were modified');
836
+ return 0;
837
+ }
838
+
839
+ async function uninstall(args) {
840
+ const options = {
841
+ dryRun: args.includes('--dry-run'),
842
+ force: args.includes('--force'),
843
+ forceLocal: args.includes('--local'),
844
+ forceGlobal: args.includes('--global'),
845
+ purge: args.includes('--purge'),
846
+ };
847
+
848
+ // §4.3 Step 1: Read config
849
+ const config = getConfig();
850
+
851
+ // §4.3 Step 1: nothing installed, or already uninstalled → clean exit (AC-09)
852
+ if (isAlreadyGone(config)) return 0;
853
+
854
+ const prepared = prepareUninstallPlan(config, options);
855
+ if (prepared.mode === null) return 0;
856
+ const { mode, plan, purgeDirs } = prepared;
857
+
858
+ if (plan.length === 0 && purgeDirs.length === 0) return recordNothingToDo(config);
859
+
860
+ const retained = printUninstallPlan(mode, plan, purgeDirs, options);
861
+ if (options.dryRun) return reportDryRun();
862
+
863
+ // §4.3 Step 6: Confirm
864
+ // Skipped in test environment since we use --force or non-interactive
865
+ // In real usage with TTY, would prompt here
866
+
867
+ const { hadErrors, backupMeta } = executeUninstallPlan(plan, config, purgeDirs, options);
725
868
 
726
869
  // Print summary
727
870
  console.log('\nUninstall complete');