wizz-method 2.0.0 → 2.1.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 (310) hide show
  1. package/LICENSE +60 -30
  2. package/README.md +80 -31
  3. package/SECURITY.md +24 -0
  4. package/THIRD-PARTY-NOTICES.md +136 -0
  5. package/package.json +31 -17
  6. package/skills-registry.yaml +128 -7
  7. package/src/bmm-skills/1-analysis/research/wizz-domain-research/SKILL.md +3 -4
  8. package/src/bmm-skills/1-analysis/research/wizz-domain-research/domain-steps/step-06-research-synthesis.md +1 -1
  9. package/src/bmm-skills/1-analysis/research/wizz-market-research/SKILL.md +3 -4
  10. package/src/bmm-skills/1-analysis/research/wizz-market-research/steps/step-06-research-completion.md +1 -1
  11. package/src/bmm-skills/1-analysis/research/wizz-technical-research/SKILL.md +3 -4
  12. package/src/bmm-skills/1-analysis/research/wizz-technical-research/technical-steps/step-06-research-synthesis.md +1 -1
  13. package/src/bmm-skills/1-analysis/wizz-agent-analyst/SKILL.md +3 -4
  14. package/src/bmm-skills/1-analysis/wizz-agent-tech-writer/SKILL.md +3 -4
  15. package/src/bmm-skills/1-analysis/wizz-document-project/SKILL.md +3 -4
  16. package/src/bmm-skills/1-analysis/wizz-document-project/workflows/deep-dive-instructions.md +1 -1
  17. package/src/bmm-skills/1-analysis/wizz-document-project/workflows/full-scan-instructions.md +1 -1
  18. package/src/bmm-skills/1-analysis/wizz-prfaq/SKILL.md +3 -4
  19. package/src/bmm-skills/1-analysis/wizz-prfaq/references/verdict.md +1 -1
  20. package/src/bmm-skills/1-analysis/wizz-product-brief/SKILL.md +1 -1
  21. package/src/bmm-skills/2-plan-workflows/wizz-agent-pm/SKILL.md +3 -4
  22. package/src/bmm-skills/2-plan-workflows/wizz-agent-ux-designer/SKILL.md +3 -4
  23. package/src/bmm-skills/2-plan-workflows/wizz-create-prd/SKILL.md +1 -1
  24. package/src/bmm-skills/2-plan-workflows/wizz-edit-prd/SKILL.md +1 -1
  25. package/src/bmm-skills/2-plan-workflows/wizz-prd/SKILL.md +1 -1
  26. package/src/bmm-skills/2-plan-workflows/wizz-ux/SKILL.md +1 -1
  27. package/src/bmm-skills/2-plan-workflows/wizz-validate-prd/SKILL.md +1 -1
  28. package/src/bmm-skills/3-solutioning/wizz-agent-architect/SKILL.md +3 -4
  29. package/src/bmm-skills/3-solutioning/wizz-architecture/SKILL.md +9 -9
  30. package/src/bmm-skills/3-solutioning/wizz-architecture/references/headless.md +1 -1
  31. package/src/bmm-skills/3-solutioning/wizz-check-implementation-readiness/SKILL.md +3 -4
  32. package/src/bmm-skills/3-solutioning/wizz-check-implementation-readiness/steps/step-06-final-assessment.md +1 -1
  33. package/src/bmm-skills/3-solutioning/wizz-create-architecture/SKILL.md +1 -1
  34. package/src/bmm-skills/3-solutioning/wizz-create-epics-and-stories/SKILL.md +3 -4
  35. package/src/bmm-skills/3-solutioning/wizz-create-epics-and-stories/steps/step-04-final-validation.md +1 -1
  36. package/src/bmm-skills/3-solutioning/wizz-generate-project-context/SKILL.md +3 -4
  37. package/src/bmm-skills/3-solutioning/wizz-generate-project-context/steps/step-03-complete.md +1 -1
  38. package/src/bmm-skills/4-implementation/wizz-agent-dev/SKILL.md +3 -4
  39. package/src/bmm-skills/4-implementation/wizz-checkpoint-preview/SKILL.md +3 -4
  40. package/src/bmm-skills/4-implementation/wizz-checkpoint-preview/step-05-wrapup.md +1 -1
  41. package/src/bmm-skills/4-implementation/wizz-code-review/SKILL.md +3 -4
  42. package/src/bmm-skills/4-implementation/wizz-code-review/customize.toml +3 -8
  43. package/src/bmm-skills/4-implementation/wizz-code-review/review-prompts/blind-hunter.md +20 -0
  44. package/src/bmm-skills/4-implementation/wizz-code-review/steps/step-04-present.md +1 -1
  45. package/src/bmm-skills/4-implementation/wizz-correct-course/SKILL.md +4 -5
  46. package/src/bmm-skills/4-implementation/wizz-create-story/SKILL.md +4 -5
  47. package/src/bmm-skills/4-implementation/wizz-dev-story/SKILL.md +4 -5
  48. package/src/bmm-skills/4-implementation/wizz-investigate/SKILL.md +1 -1
  49. package/src/bmm-skills/4-implementation/wizz-qa-generate-e2e-tests/SKILL.md +4 -5
  50. package/src/bmm-skills/4-implementation/wizz-quick-dev/SKILL.md +4 -5
  51. package/src/bmm-skills/4-implementation/wizz-quick-dev/customize.toml +10 -22
  52. package/src/bmm-skills/4-implementation/wizz-quick-dev/review-prompts/blind-hunter.md +20 -0
  53. package/src/bmm-skills/4-implementation/wizz-quick-dev/step-05-present.md +1 -1
  54. package/src/bmm-skills/4-implementation/wizz-quick-dev/step-oneshot.md +1 -1
  55. package/src/bmm-skills/4-implementation/wizz-retrospective/SKILL.md +1 -2
  56. package/src/bmm-skills/4-implementation/wizz-sprint-planning/SKILL.md +1 -1
  57. package/src/bmm-skills/4-implementation/wizz-sprint-status/SKILL.md +5 -6
  58. package/src/core-skills/_shared/handoff-protocol.md +9 -0
  59. package/src/core-skills/wizz-advanced-elicitation/SKILL.md +2 -2
  60. package/src/core-skills/wizz-brainstorming/SKILL.md +6 -6
  61. package/src/core-skills/wizz-brainstorming/references/converge.md +1 -1
  62. package/src/core-skills/wizz-brainstorming/references/finalize.md +1 -1
  63. package/src/core-skills/wizz-brainstorming/references/headless.md +3 -3
  64. package/src/core-skills/wizz-brainstorming/references/mode-autonomous.md +1 -1
  65. package/src/core-skills/wizz-customize/SKILL.md +13 -10
  66. package/src/core-skills/wizz-forge-idea/SKILL.md +6 -6
  67. package/src/core-skills/wizz-forge-idea/scripts/__pycache__/resolve_personas.cpython-314.pyc +0 -0
  68. package/src/core-skills/wizz-forge-idea/scripts/resolve_personas.py +17 -1
  69. package/src/core-skills/wizz-party-mode/SKILL.md +3 -3
  70. package/src/core-skills/wizz-party-mode/references/create-party.md +1 -1
  71. package/src/core-skills/wizz-party-mode/references/party-memory.md +2 -2
  72. package/src/core-skills/wizz-party-mode/scripts/__pycache__/resolve_party.cpython-314.pyc +0 -0
  73. package/src/core-skills/wizz-party-mode/scripts/resolve_party.py +17 -1
  74. package/src/core-skills/wizz-review-adversarial-general/SKILL.md +1 -1
  75. package/src/core-skills/wizz-spec/SKILL.md +5 -5
  76. package/src/modules/lowticket/README.md +6 -6
  77. package/src/modules/lowticket/module.yaml +4 -1
  78. package/src/modules/lowticket/skills/{lowticket-funil → wizz-lowticket-funil}/SKILL.md +4 -4
  79. package/src/modules/lowticket/skills/{lowticket-funil → wizz-lowticket-funil}/references/copy-das-paginas.md +1 -1
  80. package/src/modules/lowticket/skills/{lowticket-metodologia → wizz-lowticket-metodologia}/SKILL.md +1 -1
  81. package/src/modules/lowticket/skills/{lowticket-minerador → wizz-lowticket-minerador}/SKILL.md +3 -3
  82. package/src/modules/lowticket/skills/{lowticket-minerador → wizz-lowticket-minerador}/references/rubrica.md +1 -1
  83. package/src/modules/lowticket/skills/{lowticket-pagina → wizz-lowticket-pagina}/SKILL.md +4 -4
  84. package/src/modules/lowticket/skills/{lowticket-trafego → wizz-lowticket-trafego}/SKILL.md +3 -3
  85. package/src/modules/lowticket/skills/{lowticket-trafego → wizz-lowticket-trafego}/references/reguas.md +1 -1
  86. package/src/modules/wizz/_shared/communication-rules.md +1 -1
  87. package/src/modules/wizz/_shared/despacho-barato.md +9 -0
  88. package/src/modules/wizz/_shared/token-economy.md +7 -0
  89. package/src/modules/wizz/agents/wizz-ads/SKILL.md +1 -1
  90. package/src/modules/wizz/agents/wizz-ads/customize.toml +1 -2
  91. package/src/modules/wizz/agents/wizz-copy/SKILL.md +1 -1
  92. package/src/modules/wizz/agents/wizz-copy/customize.toml +1 -2
  93. package/src/modules/wizz/agents/wizz-designer/SKILL.md +1 -1
  94. package/src/modules/wizz/agents/wizz-designer/customize.toml +1 -2
  95. package/src/modules/wizz/agents/wizz-growth/SKILL.md +1 -1
  96. package/src/modules/wizz/agents/wizz-growth/customize.toml +1 -2
  97. package/src/modules/wizz/agents/wizz-maestro/SKILL.md +5 -5
  98. package/src/modules/wizz/agents/wizz-maestro/customize.toml +4 -8
  99. package/src/modules/wizz/agents/wizz-memoria/SKILL.md +1 -1
  100. package/src/modules/wizz/agents/wizz-memoria/customize.toml +1 -2
  101. package/src/modules/wizz/agents/wizz-qa/SKILL.md +1 -1
  102. package/src/modules/wizz/agents/wizz-qa/customize.toml +1 -2
  103. package/src/modules/wizz/agents/wizz-seo/SKILL.md +1 -1
  104. package/src/modules/wizz/agents/wizz-seo/customize.toml +1 -2
  105. package/src/modules/wizz/agents/wizz-social/SKILL.md +1 -1
  106. package/src/modules/wizz/agents/wizz-social/customize.toml +1 -2
  107. package/src/modules/wizz/module.yaml +3 -0
  108. package/src/modules/wizz/overrides/wizz-agent-analyst.toml +1 -2
  109. package/src/modules/wizz/overrides/wizz-agent-architect.toml +1 -2
  110. package/src/modules/wizz/overrides/wizz-agent-dev.toml +1 -2
  111. package/src/modules/wizz/overrides/wizz-agent-pm.toml +1 -2
  112. package/src/modules/wizz/overrides/wizz-agent-tech-writer.toml +1 -2
  113. package/src/modules/wizz/overrides/wizz-agent-ux-designer.toml +1 -2
  114. package/src/modules/wizz/subagents/codex/wizz-exec-haiku.toml +2 -0
  115. package/src/modules/wizz/subagents/codex/wizz-exec-opus.toml +2 -0
  116. package/src/modules/wizz/subagents/codex/wizz-exec-review.toml +2 -0
  117. package/src/modules/wizz/subagents/codex/wizz-exec-sonnet.toml +2 -0
  118. package/src/modules/wizz/subagents/gemini/wizz-exec-haiku.md +4 -1
  119. package/src/modules/wizz/subagents/gemini/wizz-exec-opus.md +4 -1
  120. package/src/modules/wizz/subagents/gemini/wizz-exec-review.md +4 -1
  121. package/src/modules/wizz/subagents/gemini/wizz-exec-sonnet.md +4 -1
  122. package/src/modules/wizz/subagents/opencode/wizz-exec-haiku.md +4 -1
  123. package/src/modules/wizz/subagents/opencode/wizz-exec-opus.md +4 -1
  124. package/src/modules/wizz/subagents/opencode/wizz-exec-review.md +4 -1
  125. package/src/modules/wizz/subagents/opencode/wizz-exec-sonnet.md +4 -1
  126. package/src/modules/wizz/subagents/spec.yaml +148 -0
  127. package/src/modules/wizz/subagents/wizz-exec-haiku.md +4 -1
  128. package/src/modules/wizz/subagents/wizz-exec-opus.md +4 -1
  129. package/src/modules/wizz/subagents/wizz-exec-review.md +4 -1
  130. package/src/modules/wizz/subagents/wizz-exec-sonnet.md +4 -1
  131. package/src/scripts/__pycache__/resolve_customization.cpython-314.pyc +0 -0
  132. package/src/scripts/memlog.js +368 -0
  133. package/src/scripts/resolve_customization.py +124 -15
  134. package/src/skills-lib/_shared/complexity-signal.md +14 -0
  135. package/src/skills-lib/wizz-canvas-design/canvas-fonts/InstrumentSerif-OFL.txt +93 -0
  136. package/src/skills-lib/wizz-huashu-design/references/sfx-library.md +1 -1
  137. package/src/skills-lib/wizz-huashu-design/scripts/add-music.sh +1 -1
  138. package/src/skills-lib/wizz-huashu-design/scripts/mix-voiceover.sh +1 -1
  139. package/src/skills-lib/wizz-impeccable/LICENSE.txt +202 -0
  140. package/src/skills-lib/wizz-offer-forge/SKILL.md +1 -1
  141. package/src/skills-lib/wizz-react-components/LICENSE.txt +202 -0
  142. package/src/skills-lib/wizz-router/SKILL.md +2 -2
  143. package/src/skills-lib/wizz-supabase-postgres-best-practices/LICENSE +21 -0
  144. package/src/skills-lib/wizz-taste-skill/SKILL.md +1 -1
  145. package/src/skills-lib/wizz-tracking-audit/SKILL.md +1 -1
  146. package/tools/fetch-assets.mjs +62 -37
  147. package/tools/hooks/README.md +22 -0
  148. package/tools/hooks/rtk-rewrite.sh +280 -0
  149. package/tools/hooks/security-defensive-context.js +70 -0
  150. package/tools/hooks/session-rules.js +368 -0
  151. package/tools/hooks/wizz-decision-trace.js +389 -0
  152. package/tools/hooks/wizz-router-enforce.js +258 -0
  153. package/tools/installer/banner.js +1 -1
  154. package/tools/installer/commands/doctor.js +124 -0
  155. package/tools/installer/commands/install.js +1 -1
  156. package/tools/installer/commands/resolve.js +95 -0
  157. package/tools/installer/core/doctor.js +648 -0
  158. package/tools/installer/core/hash-cache.js +156 -0
  159. package/tools/installer/core/help-catalog.js +4 -1
  160. package/tools/installer/core/hooks-settings.js +178 -0
  161. package/tools/installer/core/installer.js +297 -15
  162. package/tools/installer/core/legacy-warnings.js +0 -4
  163. package/tools/installer/core/manifest-generator.js +121 -43
  164. package/tools/installer/core/manifest.js +36 -32
  165. package/tools/installer/core/module-config-writer.js +4 -1
  166. package/tools/installer/core/python-check.js +60 -63
  167. package/tools/installer/core/quick-update.js +76 -43
  168. package/tools/installer/core/resolved-config.js +168 -0
  169. package/tools/installer/core/resolved-customizations.js +736 -0
  170. package/tools/installer/core/resolved-includes.js +262 -0
  171. package/tools/installer/core/resolved-schema.js +148 -0
  172. package/tools/installer/core/user-file-preservation.js +40 -8
  173. package/tools/installer/core/wizz-dir.js +117 -0
  174. package/tools/installer/core/yaml-cache.js +105 -0
  175. package/tools/installer/fs-native.js +97 -6
  176. package/tools/installer/ide/_config-driven.js +12 -75
  177. package/tools/installer/ide/platform-codes.js +111 -16
  178. package/tools/installer/ide/platform-codes.yaml +45 -100
  179. package/tools/installer/ide/shared/path-utils.js +6 -208
  180. package/tools/installer/install-messages.yaml +4 -14
  181. package/tools/installer/modules/channel-plan.js +15 -2
  182. package/tools/installer/modules/config-collector.js +762 -0
  183. package/tools/installer/modules/config-values.js +352 -0
  184. package/tools/installer/modules/custom-module-manager.js +161 -28
  185. package/tools/installer/modules/env-vars.js +119 -0
  186. package/tools/installer/modules/external-manager.js +133 -60
  187. package/tools/installer/modules/git-cache-utils.js +125 -0
  188. package/tools/installer/modules/module-catalog.js +565 -0
  189. package/tools/installer/modules/module-installer.js +618 -0
  190. package/tools/installer/modules/module-interface.js +86 -0
  191. package/tools/installer/modules/official-modules.js +98 -2172
  192. package/tools/installer/modules/pin-spec.js +125 -0
  193. package/tools/installer/modules/plugin-resolver.js +4 -0
  194. package/tools/installer/modules/skills-lib.js +3 -6
  195. package/tools/installer/prompts.js +0 -3
  196. package/tools/installer/ui.js +89 -54
  197. package/tools/installer/wizz-cli.js +1 -1
  198. package/tools/lib/frontmatter.js +139 -0
  199. package/tools/lib/sync-targets.mjs +49 -0
  200. package/tools/lib/walk.js +93 -0
  201. package/wizz-modules.yaml +9 -0
  202. package/src/scripts/__pycache__/memlog.cpython-313.pyc +0 -0
  203. package/src/scripts/memlog.py +0 -233
  204. package/src/scripts/tests/__pycache__/test_memlog.cpython-313-pytest-9.1.1.pyc +0 -0
  205. package/src/scripts/tests/__pycache__/test_resolve_customization.cpython-313-pytest-9.1.1.pyc +0 -0
  206. package/src/scripts/tests/test_memlog.py +0 -306
  207. package/src/skills-lib/wizz-huashu-design/assets/showcases/INDEX.md +0 -115
  208. package/src/skills-lib/wizz-huashu-design/assets/showcases/cover/cover-build.html +0 -235
  209. package/src/skills-lib/wizz-huashu-design/assets/showcases/cover/cover-build.png +0 -0
  210. package/src/skills-lib/wizz-huashu-design/assets/showcases/cover/cover-pentagram.html +0 -229
  211. package/src/skills-lib/wizz-huashu-design/assets/showcases/cover/cover-pentagram.png +0 -0
  212. package/src/skills-lib/wizz-huashu-design/assets/showcases/cover/cover-takram.html +0 -288
  213. package/src/skills-lib/wizz-huashu-design/assets/showcases/cover/cover-takram.png +0 -0
  214. package/src/skills-lib/wizz-huashu-design/assets/showcases/infographic/infographic-build.html +0 -503
  215. package/src/skills-lib/wizz-huashu-design/assets/showcases/infographic/infographic-build.png +0 -0
  216. package/src/skills-lib/wizz-huashu-design/assets/showcases/infographic/infographic-pentagram.html +0 -600
  217. package/src/skills-lib/wizz-huashu-design/assets/showcases/infographic/infographic-pentagram.png +0 -0
  218. package/src/skills-lib/wizz-huashu-design/assets/showcases/infographic/infographic-takram.html +0 -670
  219. package/src/skills-lib/wizz-huashu-design/assets/showcases/infographic/infographic-takram.png +0 -0
  220. package/src/skills-lib/wizz-huashu-design/assets/showcases/ppt/ppt-build.html +0 -382
  221. package/src/skills-lib/wizz-huashu-design/assets/showcases/ppt/ppt-build.png +0 -0
  222. package/src/skills-lib/wizz-huashu-design/assets/showcases/ppt/ppt-pentagram.html +0 -536
  223. package/src/skills-lib/wizz-huashu-design/assets/showcases/ppt/ppt-pentagram.png +0 -0
  224. package/src/skills-lib/wizz-huashu-design/assets/showcases/ppt/ppt-takram.html +0 -497
  225. package/src/skills-lib/wizz-huashu-design/assets/showcases/ppt/ppt-takram.png +0 -0
  226. package/src/skills-lib/wizz-huashu-design/assets/showcases/website-ai-nav/ainav-build.html +0 -385
  227. package/src/skills-lib/wizz-huashu-design/assets/showcases/website-ai-nav/ainav-build.png +0 -0
  228. package/src/skills-lib/wizz-huashu-design/assets/showcases/website-ai-nav/ainav-pentagram.html +0 -422
  229. package/src/skills-lib/wizz-huashu-design/assets/showcases/website-ai-nav/ainav-pentagram.png +0 -0
  230. package/src/skills-lib/wizz-huashu-design/assets/showcases/website-ai-nav/ainav-takram.html +0 -499
  231. package/src/skills-lib/wizz-huashu-design/assets/showcases/website-ai-nav/ainav-takram.png +0 -0
  232. package/src/skills-lib/wizz-huashu-design/assets/showcases/website-ai-writing/aiwriting-build.html +0 -562
  233. package/src/skills-lib/wizz-huashu-design/assets/showcases/website-ai-writing/aiwriting-build.png +0 -0
  234. package/src/skills-lib/wizz-huashu-design/assets/showcases/website-ai-writing/aiwriting-pentagram.html +0 -548
  235. package/src/skills-lib/wizz-huashu-design/assets/showcases/website-ai-writing/aiwriting-pentagram.png +0 -0
  236. package/src/skills-lib/wizz-huashu-design/assets/showcases/website-ai-writing/aiwriting-takram.html +0 -696
  237. package/src/skills-lib/wizz-huashu-design/assets/showcases/website-ai-writing/aiwriting-takram.png +0 -0
  238. package/src/skills-lib/wizz-huashu-design/assets/showcases/website-devdocs/devdocs-build.html +0 -372
  239. package/src/skills-lib/wizz-huashu-design/assets/showcases/website-devdocs/devdocs-build.png +0 -0
  240. package/src/skills-lib/wizz-huashu-design/assets/showcases/website-devdocs/devdocs-pentagram.html +0 -460
  241. package/src/skills-lib/wizz-huashu-design/assets/showcases/website-devdocs/devdocs-pentagram.png +0 -0
  242. package/src/skills-lib/wizz-huashu-design/assets/showcases/website-devdocs/devdocs-takram.html +0 -494
  243. package/src/skills-lib/wizz-huashu-design/assets/showcases/website-devdocs/devdocs-takram.png +0 -0
  244. package/src/skills-lib/wizz-huashu-design/assets/showcases/website-homepage/homepage-build.html +0 -367
  245. package/src/skills-lib/wizz-huashu-design/assets/showcases/website-homepage/homepage-build.png +0 -0
  246. package/src/skills-lib/wizz-huashu-design/assets/showcases/website-homepage/homepage-pentagram.html +0 -368
  247. package/src/skills-lib/wizz-huashu-design/assets/showcases/website-homepage/homepage-pentagram.png +0 -0
  248. package/src/skills-lib/wizz-huashu-design/assets/showcases/website-homepage/homepage-takram.html +0 -459
  249. package/src/skills-lib/wizz-huashu-design/assets/showcases/website-homepage/homepage-takram.png +0 -0
  250. package/src/skills-lib/wizz-huashu-design/assets/showcases/website-saas/saas-build.html +0 -493
  251. package/src/skills-lib/wizz-huashu-design/assets/showcases/website-saas/saas-build.png +0 -0
  252. package/src/skills-lib/wizz-huashu-design/assets/showcases/website-saas/saas-pentagram.html +0 -556
  253. package/src/skills-lib/wizz-huashu-design/assets/showcases/website-saas/saas-pentagram.png +0 -0
  254. package/src/skills-lib/wizz-huashu-design/assets/showcases/website-saas/saas-takram.html +0 -604
  255. package/src/skills-lib/wizz-huashu-design/assets/showcases/website-saas/saas-takram.png +0 -0
  256. package/tools/installer/file-ops.js +0 -204
  257. package/tools/installer/ide/shared/skill-manifest.js +0 -57
  258. package/tools/installer/yaml-format.js +0 -245
  259. package/web-bundles/README.md +0 -46
  260. package/web-bundles/brainstorming-coach/INSTRUCTIONS.md +0 -86
  261. package/web-bundles/brainstorming-coach/SKILL.md +0 -83
  262. package/web-bundles/brainstorming-coach/brain-methods.csv +0 -62
  263. package/web-bundles/bundles.json +0 -139
  264. package/web-bundles/market-and-industry-research/INSTRUCTIONS.md +0 -88
  265. package/web-bundles/market-and-industry-research/SKILL.md +0 -59
  266. package/web-bundles/prd-coach/INSTRUCTIONS.md +0 -86
  267. package/web-bundles/prd-coach/SKILL.md +0 -101
  268. package/web-bundles/prd-coach/prd-template.md +0 -165
  269. package/web-bundles/prd-coach/prd-validation-checklist.md +0 -135
  270. package/web-bundles/prfaq-coach/INSTRUCTIONS.md +0 -86
  271. package/web-bundles/prfaq-coach/SKILL.md +0 -139
  272. package/web-bundles/product-brief-coach/INSTRUCTIONS.md +0 -86
  273. package/web-bundles/product-brief-coach/SKILL.md +0 -113
  274. package/web-bundles/ux-coach/INSTRUCTIONS.md +0 -92
  275. package/web-bundles/ux-coach/SKILL.md +0 -187
  276. package/web-bundles/ux-coach/ux-validation.md +0 -100
  277. /package/src/modules/lowticket/skills/{lowticket-funil → wizz-lowticket-funil}/references/mapa-do-funil.md +0 -0
  278. /package/src/modules/lowticket/skills/{lowticket-metodologia → wizz-lowticket-metodologia}/CATALOGO.md +0 -0
  279. /package/src/modules/lowticket/skills/{lowticket-metodologia → wizz-lowticket-metodologia}/knowledge/01-principios.md +0 -0
  280. /package/src/modules/lowticket/skills/{lowticket-metodologia → wizz-lowticket-metodologia}/knowledge/02-diagnostico-funil.md +0 -0
  281. /package/src/modules/lowticket/skills/{lowticket-metodologia → wizz-lowticket-metodologia}/knowledge/03-campanha-bidcap.md +0 -0
  282. /package/src/modules/lowticket/skills/{lowticket-metodologia → wizz-lowticket-metodologia}/knowledge/04-criativos.md +0 -0
  283. /package/src/modules/lowticket/skills/{lowticket-metodologia → wizz-lowticket-metodologia}/knowledge/04a-criativos-ia.md +0 -0
  284. /package/src/modules/lowticket/skills/{lowticket-metodologia → wizz-lowticket-metodologia}/knowledge/04b-criativos-formatos.md +0 -0
  285. /package/src/modules/lowticket/skills/{lowticket-metodologia → wizz-lowticket-metodologia}/knowledge/05-oferta.md +0 -0
  286. /package/src/modules/lowticket/skills/{lowticket-metodologia → wizz-lowticket-metodologia}/knowledge/06-pagina-vendas.md +0 -0
  287. /package/src/modules/lowticket/skills/{lowticket-metodologia → wizz-lowticket-metodologia}/knowledge/06a-instagram.md +0 -0
  288. /package/src/modules/lowticket/skills/{lowticket-metodologia → wizz-lowticket-metodologia}/knowledge/06b-player-vsl.md +0 -0
  289. /package/src/modules/lowticket/skills/{lowticket-metodologia → wizz-lowticket-metodologia}/knowledge/07-funil-upsell.md +0 -0
  290. /package/src/modules/lowticket/skills/{lowticket-metodologia → wizz-lowticket-metodologia}/knowledge/07a-copy-humanizacao.md +0 -0
  291. /package/src/modules/lowticket/skills/{lowticket-metodologia → wizz-lowticket-metodologia}/knowledge/08-pesquisa-publico.md +0 -0
  292. /package/src/modules/lowticket/skills/{lowticket-metodologia → wizz-lowticket-metodologia}/knowledge/09-especialista-coproducao.md +0 -0
  293. /package/src/modules/lowticket/skills/{lowticket-metodologia → wizz-lowticket-metodologia}/knowledge/10-levantar-caixa.md +0 -0
  294. /package/src/modules/lowticket/skills/{lowticket-metodologia → wizz-lowticket-metodologia}/knowledge/11-checklist-roi.md +0 -0
  295. /package/src/modules/lowticket/skills/{lowticket-metodologia → wizz-lowticket-metodologia}/knowledge/12-mineracao-ofertas.md +0 -0
  296. /package/src/modules/lowticket/skills/{lowticket-metodologia → wizz-lowticket-metodologia}/knowledge/12a-mineracao-veredito.md +0 -0
  297. /package/src/modules/lowticket/skills/{lowticket-metodologia → wizz-lowticket-metodologia}/knowledge/12b-fabrica-de-ofertas.md +0 -0
  298. /package/src/modules/lowticket/skills/{lowticket-metodologia → wizz-lowticket-metodologia}/knowledge/12c-anatomia-low-ticket.md +0 -0
  299. /package/src/modules/lowticket/skills/{lowticket-metodologia → wizz-lowticket-metodologia}/knowledge/13-benchmarks-vsl.md +0 -0
  300. /package/src/modules/lowticket/skills/{lowticket-metodologia → wizz-lowticket-metodologia}/knowledge/14-vocabulario.md +0 -0
  301. /package/src/modules/lowticket/skills/{lowticket-metodologia → wizz-lowticket-metodologia}/knowledge/15-como-estender.md +0 -0
  302. /package/src/modules/lowticket/skills/{lowticket-metodologia → wizz-lowticket-metodologia}/knowledge/17-rastreamento.md +0 -0
  303. /package/src/modules/lowticket/skills/{lowticket-metodologia → wizz-lowticket-metodologia}/knowledge/18-copy-desejo-oferta.md +0 -0
  304. /package/src/modules/lowticket/skills/{lowticket-metodologia → wizz-lowticket-metodologia}/knowledge/INDEX.md +0 -0
  305. /package/src/modules/lowticket/skills/{lowticket-metodologia → wizz-lowticket-metodologia}/knowledge/guardrails.md +0 -0
  306. /package/src/modules/lowticket/skills/{lowticket-metodologia → wizz-lowticket-metodologia}/knowledge/pontos-em-aberto.md +0 -0
  307. /package/src/modules/lowticket/skills/{lowticket-metodologia → wizz-lowticket-metodologia}/references/swipe-file.md +0 -0
  308. /package/src/modules/lowticket/skills/{lowticket-pagina → wizz-lowticket-pagina}/references/metas-e-medicao.md +0 -0
  309. /package/src/modules/lowticket/skills/{lowticket-pagina → wizz-lowticket-pagina}/references/padroes-de-codigo.md +0 -0
  310. /package/src/modules/lowticket/skills/{lowticket-trafego → wizz-lowticket-trafego}/references/formato-do-diagnostico.md +0 -0
@@ -1,10 +1,8 @@
1
- const path = require('node:path');
2
- const fs = require('../fs-native');
3
- const yaml = require('yaml');
4
1
  const prompts = require('../prompts');
5
- const { getProjectRoot, getSourcePath, getModulePath } = require('../project-root');
6
- const { CLIUtils } = require('../banner');
7
2
  const { ExternalModuleManager } = require('./external-manager');
3
+ const { ModuleCatalog, isMissingDefault: isMissingDefaultShared } = require('./module-catalog');
4
+ const { ModuleInstallerMethods } = require('./module-installer');
5
+ const { ConfigCollectorMethods } = require('./config-collector');
8
6
 
9
7
  class OfficialModules {
10
8
  /**
@@ -16,22 +14,28 @@ class OfficialModules {
16
14
  * @returns {boolean} True when the field has no usable default.
17
15
  */
18
16
  static isMissingDefault(defaultValue) {
19
- return defaultValue === undefined || defaultValue === null;
17
+ return isMissingDefaultShared(defaultValue);
20
18
  }
21
19
 
22
20
  constructor(options = {}) {
23
21
  this.externalModuleManager = new ExternalModuleManager();
22
+ // Camada de leitura pura (item 20, etapa 2). Compartilha o mesmo
23
+ // externalModuleManager: as resoluções de canal/pin gravadas durante a
24
+ // coleta de config precisam ser as mesmas vistas no install.
25
+ this.catalog = new ModuleCatalog({
26
+ externalModuleManager: this.externalModuleManager,
27
+ channelOptions: options.channelOptions || null,
28
+ // Ponto único de override: tudo que o catálogo resolve internamente
29
+ // passa por este wrapper, então stubar `officialModules.findModuleSource`
30
+ // (padrão de test-atomic-writes.js) cobre também listAvailable,
31
+ // getModuleInfo e scanModuleSchemas.
32
+ findModuleSource: (code, opts) => this.findModuleSource(code, opts),
33
+ });
24
34
  // Config collection state (merged from ConfigCollector)
25
35
  this.collectedConfig = {};
26
- this._existingConfig = null;
27
36
  // Tracked during interactive config collection so {directory_name}
28
37
  // placeholder defaults can be resolved in buildQuestion().
29
38
  this.currentProjectDir = null;
30
- // Install-time channel flag state. Set by Config.build once, then used as
31
- // the default for every findModuleSource/cloneExternalModule call so that
32
- // pre-install config collection and the install step agree on which ref
33
- // to clone.
34
- this.channelOptions = options.channelOptions || null;
35
39
  }
36
40
 
37
41
  /**
@@ -41,6 +45,22 @@ class OfficialModules {
41
45
  return this.collectedConfig;
42
46
  }
43
47
 
48
+ /**
49
+ * Existing module configurations read from a previous installation.
50
+ *
51
+ * Lê o armazém do catálogo direto (item 20, auditoria 2026-09-11): antes
52
+ * `_existingConfig` era um *snapshot* copiado em loadExistingConfig, e
53
+ * qualquer repopulação do catálogo (ou uma chamada isolada de
54
+ * `catalog.loadExistingConfig`) deixava os dois lados divergentes.
55
+ */
56
+ get _existingConfig() {
57
+ return this.catalog.existingConfigData || null;
58
+ }
59
+
60
+ set _existingConfig(value) {
61
+ this.catalog.existingConfigData = value;
62
+ }
63
+
44
64
  /**
45
65
  * Existing module configurations read from a previous installation.
46
66
  */
@@ -48,6 +68,21 @@ class OfficialModules {
48
68
  return this._existingConfig;
49
69
  }
50
70
 
71
+ /**
72
+ * Install-time channel flag state. Set by Config.build once, then used as
73
+ * the default for every findModuleSource/cloneExternalModule call so that
74
+ * pre-install config collection and the install step agree on which ref
75
+ * to clone. Encaminhado ao catálogo (quem de fato lê o valor) para que uma
76
+ * atribuição externa não vire um no-op silencioso.
77
+ */
78
+ get channelOptions() {
79
+ return this.catalog.channelOptions;
80
+ }
81
+
82
+ set channelOptions(value) {
83
+ this.catalog.channelOptions = value || null;
84
+ }
85
+
51
86
  /**
52
87
  * Build a configured OfficialModules instance from install config.
53
88
  * @param {Object} config - Clean install config (from Config.build)
@@ -83,747 +118,37 @@ class OfficialModules {
83
118
  }
84
119
 
85
120
  /**
86
- * Copy a file to the target location
87
- * @param {string} sourcePath - Source file path
88
- * @param {string} targetPath - Target file path
89
- * @param {boolean} overwrite - Whether to overwrite existing files (default: true)
90
- */
91
- async copyFile(sourcePath, targetPath, overwrite = true) {
92
- await fs.copy(sourcePath, targetPath, { overwrite });
93
- }
94
-
95
- /**
96
- * Copy a directory recursively
97
- * @param {string} sourceDir - Source directory path
98
- * @param {string} targetDir - Target directory path
99
- * @param {boolean} overwrite - Whether to overwrite existing files (default: true)
121
+ * Emit the warnings the catalog could not emit itself (it must not import
122
+ * `prompts`). Restaura o comportamento pré-split: um module.yaml ilegível
123
+ * gerava um `log.warn` por módulo em vez de um `catch {}` mudo.
100
124
  */
101
- async copyDirectory(sourceDir, targetDir, overwrite = true) {
102
- await fs.ensureDir(targetDir);
103
- const entries = await fs.readdir(sourceDir, { withFileTypes: true });
104
-
105
- for (const entry of entries) {
106
- const sourcePath = path.join(sourceDir, entry.name);
107
- const targetPath = path.join(targetDir, entry.name);
108
-
109
- if (entry.isDirectory()) {
110
- await this.copyDirectory(sourcePath, targetPath, overwrite);
111
- } else {
112
- await this.copyFile(sourcePath, targetPath, overwrite);
113
- }
125
+ async _flushCatalogLoadErrors() {
126
+ for (const { module, error } of this.catalog.takeLoadErrors()) {
127
+ await prompts.log.warn(`Could not read module.yaml for "${module}": ${error.message}`);
114
128
  }
115
129
  }
116
130
 
117
131
  /**
118
- * List all available built-in modules (core and bmm).
119
- * All other modules come from external-official-modules.yaml
120
- * @returns {Object} Object with modules array
132
+ * Leitura de módulos (listar, descrever, localizar fonte) — delegada ao
133
+ * ModuleCatalog (item 20, etapa 2). A classe mantém os métodos como wrappers
134
+ * finos para compatibilidade com os callers existentes (ui.js, quick-update,
135
+ * installer core, testes que monkey-patcham estes prototypes).
121
136
  */
122
- async listAvailable() {
123
- const modules = [];
124
-
125
- // Add built-in core module (directly under src/core-skills)
126
- const corePath = getSourcePath('core-skills');
127
- if (await fs.pathExists(corePath)) {
128
- const coreInfo = await this.getModuleInfo(corePath, 'core', 'src/core-skills');
129
- if (coreInfo) {
130
- modules.push(coreInfo);
131
- }
132
- }
133
-
134
- // Add built-in bmm module (directly under src/bmm-skills)
135
- const bmmPath = getSourcePath('bmm-skills');
136
- if (await fs.pathExists(bmmPath)) {
137
- const bmmInfo = await this.getModuleInfo(bmmPath, 'bmm', 'src/bmm-skills');
138
- if (bmmInfo) {
139
- modules.push(bmmInfo);
140
- }
141
- }
142
137
 
143
- // Add bundled local modules (src/modules/<code>), e.g. wizz. Without this
144
- // they never appear in the picker nor in the --yes defaults, even with
145
- // default_selected: true — findModuleSource resolves them, but nothing
146
- // ever selects them (bug: maestro/agentes de área não instalavam via npx).
147
- const bundledDir = getSourcePath('modules');
148
- if (await fs.pathExists(bundledDir)) {
149
- const entries = await fs.readdir(bundledDir, { withFileTypes: true });
150
- const seen = new Set(modules.map((m) => m.id));
151
- for (const entry of entries) {
152
- if (!entry.isDirectory()) continue;
153
- const modulePath = path.join(bundledDir, entry.name);
154
- if (!(await fs.pathExists(path.join(modulePath, 'module.yaml')))) continue;
155
- const info = await this.getModuleInfo(modulePath, entry.name, `src/modules/${entry.name}`);
156
- if (info && !seen.has(info.id)) {
157
- modules.push(info);
158
- seen.add(info.id);
159
- }
160
- }
161
- }
162
-
163
- return { modules };
138
+ async listAvailable() {
139
+ const result = await this.catalog.listAvailable();
140
+ await this._flushCatalogLoadErrors();
141
+ return result;
164
142
  }
165
143
 
166
- /**
167
- * Get module information from a module path
168
- * @param {string} modulePath - Path to the module directory
169
- * @param {string} defaultName - Default name for the module
170
- * @param {string} sourceDescription - Description of where the module was found
171
- * @returns {Object|null} Module info or null if not a valid module
172
- */
173
144
  async getModuleInfo(modulePath, defaultName, sourceDescription) {
174
- const moduleConfigPath = path.join(modulePath, 'module.yaml');
175
-
176
- if (!(await fs.pathExists(moduleConfigPath))) {
177
- // Check resolution cache for strategy 5 modules (no module.yaml on disk)
178
- const { CustomModuleManager } = require('./custom-module-manager');
179
- const customMgr = new CustomModuleManager();
180
- const resolved = customMgr.getResolution(defaultName);
181
- if (resolved && resolved.synthesizedModuleYaml) {
182
- return {
183
- id: resolved.code,
184
- path: modulePath,
185
- name: resolved.name,
186
- description: resolved.description,
187
- version: resolved.version || '1.0.0',
188
- source: sourceDescription,
189
- dependencies: [],
190
- defaultSelected: false,
191
- };
192
- }
193
- return null;
194
- }
195
-
196
- const moduleInfo = {
197
- id: defaultName,
198
- path: modulePath,
199
- name: defaultName
200
- .split('-')
201
- .map((word) => word.charAt(0).toUpperCase() + word.slice(1))
202
- .join(' '),
203
- description: 'Wizz Method Module',
204
- version: '5.0.0',
205
- source: sourceDescription,
206
- };
207
-
208
- // Read module config for metadata
209
- try {
210
- const configContent = await fs.readFile(moduleConfigPath, 'utf8');
211
- const config = yaml.parse(configContent);
212
-
213
- // Use the code property as the id if available
214
- if (config.code) {
215
- moduleInfo.id = config.code;
216
- }
217
-
218
- moduleInfo.name = config.name || moduleInfo.name;
219
- moduleInfo.description = config.description || moduleInfo.description;
220
- moduleInfo.version = config.version || moduleInfo.version;
221
- moduleInfo.dependencies = config.dependencies || [];
222
- moduleInfo.defaultSelected = config.default_selected === undefined ? false : config.default_selected;
223
- } catch (error) {
224
- await prompts.log.warn(`Failed to read config for ${defaultName}: ${error.message}`);
225
- }
226
-
227
- return moduleInfo;
145
+ const info = await this.catalog.getModuleInfo(modulePath, defaultName, sourceDescription);
146
+ await this._flushCatalogLoadErrors();
147
+ return info;
228
148
  }
229
149
 
230
- /**
231
- * Find the source path for a module by searching all possible locations
232
- * @param {string} moduleCode - Code of the module to find (from module.yaml)
233
- * @returns {string|null} Path to the module source or null if not found
234
- */
235
150
  async findModuleSource(moduleCode, options = {}) {
236
- // Inherit channelOptions from the install-scoped instance when the caller
237
- // didn't pass one explicitly. Keeps pre-install config collection and the
238
- // actual install step looking at the same git ref.
239
- if (options.channelOptions === undefined && this.channelOptions) {
240
- options = { ...options, channelOptions: this.channelOptions };
241
- }
242
- const projectRoot = getProjectRoot();
243
-
244
- // Check for core module (directly under src/core-skills)
245
- if (moduleCode === 'core') {
246
- const corePath = getSourcePath('core-skills');
247
- if (await fs.pathExists(corePath)) {
248
- return corePath;
249
- }
250
- }
251
-
252
- // Check for built-in bmm module (directly under src/bmm-skills)
253
- if (moduleCode === 'bmm') {
254
- const bmmPath = getSourcePath('bmm-skills');
255
- if (await fs.pathExists(bmmPath)) {
256
- return bmmPath;
257
- }
258
- }
259
-
260
- // Check bundled local modules (directly under src/modules/<code>), e.g. wizz.
261
- // These ship inside this repo and are auto-discovered by list-options.js.
262
- const bundledPath = getSourcePath('modules', moduleCode);
263
- if (await fs.pathExists(path.join(bundledPath, 'module.yaml'))) {
264
- return bundledPath;
265
- }
266
-
267
- // Check external official modules (pass channelOptions so channel plan applies)
268
- const externalSource = await this.externalModuleManager.findExternalModuleSource(moduleCode, options);
269
- if (externalSource) {
270
- return externalSource;
271
- }
272
-
273
- // Check custom modules (from user-provided URLs, already cloned to cache)
274
- const { CustomModuleManager } = require('./custom-module-manager');
275
- const customMgr = new CustomModuleManager();
276
- const customSource = await customMgr.findModuleSourceByCode(moduleCode, options);
277
- if (customSource) {
278
- return customSource;
279
- }
280
-
281
- return null;
282
- }
283
-
284
- /**
285
- * Install a module
286
- * @param {string} moduleName - Code of the module to install (from module.yaml)
287
- * @param {string} wizzDir - Target wizz directory
288
- * @param {Function} fileTrackingCallback - Optional callback to track installed files
289
- * @param {Object} options - Additional installation options
290
- * @param {Array<string>} options.installedIDEs - Array of IDE codes that were installed
291
- * @param {Object} options.moduleConfig - Module configuration from config collector
292
- * @param {Object} options.logger - Logger instance for output
293
- */
294
- async install(moduleName, wizzDir, fileTrackingCallback = null, options = {}) {
295
- // Aliases (ex.: bauto → bmad-loop) chegam crus via --modules e via
296
- // moduleIds de instalações antigas; sem normalizar aqui, o cache de
297
- // getPluginResolution, o targetPath e o manifest usariam o código legado.
298
- moduleName = await this.externalModuleManager.resolveCanonicalCode(moduleName);
299
-
300
- // Check if this module has a plugin resolution (custom marketplace install)
301
- const { CustomModuleManager } = require('./custom-module-manager');
302
- const customMgr = new CustomModuleManager();
303
- const resolved = customMgr.getResolution(moduleName);
304
- if (resolved) {
305
- return this.installFromResolution(resolved, wizzDir, fileTrackingCallback, options);
306
- }
307
-
308
- const sourcePath = await this.findModuleSource(moduleName, {
309
- silent: options.silent,
310
- channelOptions: options.channelOptions,
311
- });
312
- const targetPath = path.join(wizzDir, moduleName);
313
-
314
- if (!sourcePath) {
315
- throw new Error(
316
- `Source for module '${moduleName}' is not available. It will be retained but cannot be updated without its source files.`,
317
- );
318
- }
319
-
320
- if (await fs.pathExists(targetPath)) {
321
- await fs.remove(targetPath);
322
- }
323
-
324
- // Módulos marketplace-plugin do registry mantêm as skills instaláveis fora do
325
- // diretório que contém o module.yaml (sourcePath aponta para o assets/ da
326
- // skill -setup), então não dá para instalá-los copiando o sourcePath. Copia
327
- // os diretórios de skill resolvidos, do mesmo jeito que um install custom de
328
- // marketplace monta um módulo. Todo o resto (manifest, versão) segue pelo
329
- // caminho padrão de módulo externo abaixo.
330
- const marketplaceInfo = await this.externalModuleManager.getModuleByCode(moduleName);
331
- if (marketplaceInfo && marketplaceInfo.marketplacePlugin) {
332
- const pluginResolution = this.externalModuleManager.getPluginResolution(moduleName);
333
- // Falha alto: copiar o sourcePath aqui instalaria só o assets/ da skill
334
- // -setup (module.yaml + module-help.csv) e nenhuma skill — um install
335
- // parcial e silenciosamente quebrado. Aborta em vez disso.
336
- if (!pluginResolution || !Array.isArray(pluginResolution.skillPaths) || pluginResolution.skillPaths.length === 0) {
337
- throw new Error(
338
- `Module '${moduleName}' is registered as a marketplace plugin but its skills could not be resolved ` +
339
- `from .claude-plugin/marketplace.json (missing or malformed on the selected channel). ` +
340
- `Aborting to avoid a partial install with no skills.`,
341
- );
342
- }
343
- await this._copyResolvedSkills(pluginResolution, targetPath, fileTrackingCallback, options.moduleConfig);
344
- } else {
345
- await this.copyModuleWithFiltering(sourcePath, targetPath, fileTrackingCallback, options.moduleConfig);
346
- }
347
-
348
- if (!options.skipModuleInstaller) {
349
- await this.createModuleDirectories(moduleName, wizzDir, options);
350
- }
351
-
352
- const { Manifest } = require('../core/manifest');
353
- const manifestObj = new Manifest();
354
- const versionInfo = await manifestObj.getModuleVersionInfo(moduleName, wizzDir, sourcePath);
355
-
356
- // Pick up channel resolution recorded by the external manager (the only
357
- // manager that does pre-clone resolution now that community is retired).
358
- const resolution = this.externalModuleManager.getResolution(moduleName);
359
-
360
- await manifestObj.addModule(wizzDir, moduleName, {
361
- version: resolution?.version || versionInfo.version,
362
- source: versionInfo.source,
363
- npmPackage: versionInfo.npmPackage,
364
- repoUrl: versionInfo.repoUrl,
365
- channel: resolution?.channel,
366
- sha: resolution?.sha,
367
- });
368
-
369
- return { success: true, module: moduleName, path: targetPath, versionInfo };
370
- }
371
-
372
- /**
373
- * Assenta em disco uma resolução do PluginResolver: copia cada diretório de
374
- * skill resolvido (achatado pelo nome da folha) para targetPath e coloca o
375
- * module-help.csv na raiz do módulo. Compartilhado pelos installs custom de
376
- * marketplace (installFromResolution) e pelos installs oficiais de módulo
377
- * marketplace-plugin (install), para os dois caminhos não divergirem.
378
- * @param {Object} resolved - ResolvedModule do PluginResolver
379
- * @param {string} targetPath - Diretório de destino do módulo (ex.: wizzDir/<code>)
380
- * @param {Function} fileTrackingCallback - Callback opcional de rastreio de arquivos
381
- * @param {Object} moduleConfig - Configuração do módulo repassada ao filtro de cópia
382
- */
383
- async _copyResolvedSkills(resolved, targetPath, fileTrackingCallback = null, moduleConfig = {}) {
384
- await fs.ensureDir(targetPath);
385
-
386
- // Copia cada diretório de skill, achatado pelo nome da folha. Os nomes de
387
- // folha precisam ser únicos — duas skills que achatam para o mesmo diretório
388
- // se sobrescreveriam em silêncio, então falha alto em vez disso.
389
- const seenLeaves = new Map();
390
- for (const skillPath of resolved.skillPaths) {
391
- const skillDirName = path.basename(skillPath);
392
- if (seenLeaves.has(skillDirName)) {
393
- throw new Error(
394
- `Cannot install module '${resolved.code}': skill directories '${seenLeaves.get(skillDirName)}' and ` +
395
- `'${skillPath}' share the leaf name '${skillDirName}' and would overwrite each other. ` +
396
- `Skill directory names must be unique.`,
397
- );
398
- }
399
- seenLeaves.set(skillDirName, skillPath);
400
- const skillTarget = path.join(targetPath, skillDirName);
401
- await this.copyModuleWithFiltering(skillPath, skillTarget, fileTrackingCallback, moduleConfig);
402
- }
403
-
404
- // Coloca o module-help.csv na raiz do módulo.
405
- const helpTarget = path.join(targetPath, 'module-help.csv');
406
- if (resolved.moduleHelpCsvPath) {
407
- // Estratégias 1-4: copia o arquivo existente.
408
- await fs.copy(resolved.moduleHelpCsvPath, helpTarget, { overwrite: true });
409
- if (fileTrackingCallback) fileTrackingCallback(helpTarget);
410
- } else if (resolved.synthesizedHelpCsv) {
411
- // Estratégia 5: escreve o conteúdo sintetizado.
412
- await fs.writeFile(helpTarget, resolved.synthesizedHelpCsv, 'utf8');
413
- if (fileTrackingCallback) fileTrackingCallback(helpTarget);
414
- }
415
- }
416
-
417
- /**
418
- * Install a module from a PluginResolver resolution result.
419
- * Copies specific skill directories and places module-help.csv at the target root.
420
- * @param {Object} resolved - ResolvedModule from PluginResolver
421
- * @param {string} wizzDir - Target wizz directory
422
- * @param {Function} fileTrackingCallback - Optional callback to track installed files
423
- * @param {Object} options - Installation options
424
- */
425
- async installFromResolution(resolved, wizzDir, fileTrackingCallback = null, options = {}) {
426
- const targetPath = path.join(wizzDir, resolved.code);
427
-
428
- if (await fs.pathExists(targetPath)) {
429
- await fs.remove(targetPath);
430
- }
431
-
432
- await this._copyResolvedSkills(resolved, targetPath, fileTrackingCallback, options.moduleConfig);
433
-
434
- // Create directories declared in module.yaml (strategies 1-4 may have these)
435
- if (!options.skipModuleInstaller) {
436
- await this.createModuleDirectories(resolved.code, wizzDir, options);
437
- }
438
-
439
- // Update manifest. For custom-source installs we derive channel from the
440
- // cloneRef (present → pinned, absent → next; local paths have no channel).
441
- const { Manifest } = require('../core/manifest');
442
- const manifestObj = new Manifest();
443
-
444
- const hasGitClone = !!resolved.repoUrl;
445
- const manifestEntry = {
446
- version: resolved.cloneRef || (hasGitClone ? 'main' : resolved.version || null),
447
- source: 'custom',
448
- npmPackage: null,
449
- repoUrl: resolved.repoUrl || null,
450
- };
451
- if (hasGitClone) {
452
- manifestEntry.channel = resolved.cloneRef ? 'pinned' : 'next';
453
- if (resolved.cloneSha) manifestEntry.sha = resolved.cloneSha;
454
- if (resolved.rawInput) manifestEntry.rawSource = resolved.rawInput;
455
- }
456
- if (resolved.localPath) manifestEntry.localPath = resolved.localPath;
457
- await manifestObj.addModule(wizzDir, resolved.code, manifestEntry);
458
-
459
- return {
460
- success: true,
461
- module: resolved.code,
462
- path: targetPath,
463
- // Mirror the manifestEntry.version precedence above so downstream summary
464
- // lines show the same string we just wrote to disk (custom git-backed
465
- // installs show the cloned ref or 'main').
466
- versionInfo: {
467
- version: resolved.cloneRef || (hasGitClone ? 'main' : resolved.version || ''),
468
- },
469
- };
470
- }
471
-
472
- /**
473
- * Update an existing module
474
- * @param {string} moduleName - Name of the module to update
475
- * @param {string} wizzDir - Target wizz directory
476
- */
477
- async update(moduleName, wizzDir) {
478
- const sourcePath = await this.findModuleSource(moduleName);
479
- const targetPath = path.join(wizzDir, moduleName);
480
-
481
- if (!sourcePath) {
482
- throw new Error(`Module '${moduleName}' not found in any source location`);
483
- }
484
-
485
- if (!(await fs.pathExists(targetPath))) {
486
- throw new Error(`Module '${moduleName}' is not installed`);
487
- }
488
-
489
- await this.syncModule(sourcePath, targetPath);
490
-
491
- return {
492
- success: true,
493
- module: moduleName,
494
- path: targetPath,
495
- };
496
- }
497
-
498
- /**
499
- * Remove a module
500
- * @param {string} moduleName - Name of the module to remove
501
- * @param {string} wizzDir - Target wizz directory
502
- */
503
- async remove(moduleName, wizzDir) {
504
- const targetPath = path.join(wizzDir, moduleName);
505
-
506
- if (!(await fs.pathExists(targetPath))) {
507
- throw new Error(`Module '${moduleName}' is not installed`);
508
- }
509
-
510
- await fs.remove(targetPath);
511
-
512
- return {
513
- success: true,
514
- module: moduleName,
515
- };
516
- }
517
-
518
- /**
519
- * Check if a module is installed
520
- * @param {string} moduleName - Name of the module
521
- * @param {string} wizzDir - Target wizz directory
522
- * @returns {boolean} True if module is installed
523
- */
524
- async isInstalled(moduleName, wizzDir) {
525
- const targetPath = path.join(wizzDir, moduleName);
526
- return await fs.pathExists(targetPath);
527
- }
528
-
529
- /**
530
- * Get installed module info
531
- * @param {string} moduleName - Name of the module
532
- * @param {string} wizzDir - Target wizz directory
533
- * @returns {Object|null} Module info or null if not installed
534
- */
535
- async getInstalledInfo(moduleName, wizzDir) {
536
- const targetPath = path.join(wizzDir, moduleName);
537
-
538
- if (!(await fs.pathExists(targetPath))) {
539
- return null;
540
- }
541
-
542
- const configPath = path.join(targetPath, 'config.yaml');
543
- const moduleInfo = {
544
- id: moduleName,
545
- path: targetPath,
546
- installed: true,
547
- };
548
-
549
- if (await fs.pathExists(configPath)) {
550
- try {
551
- const configContent = await fs.readFile(configPath, 'utf8');
552
- const config = yaml.parse(configContent);
553
- Object.assign(moduleInfo, config);
554
- } catch (error) {
555
- await prompts.log.warn(`Failed to read installed module config: ${error.message}`);
556
- }
557
- }
558
-
559
- return moduleInfo;
560
- }
561
-
562
- /**
563
- * Copy module with filtering for localskip agents and conditional content
564
- * @param {string} sourcePath - Source module path
565
- * @param {string} targetPath - Target module path
566
- * @param {Function} fileTrackingCallback - Optional callback to track installed files
567
- * @param {Object} moduleConfig - Module configuration with conditional flags
568
- */
569
- async copyModuleWithFiltering(sourcePath, targetPath, fileTrackingCallback = null, moduleConfig = {}) {
570
- // Get all files in source
571
- const sourceFiles = await this.getFileList(sourcePath);
572
-
573
- for (const file of sourceFiles) {
574
- // Skip sub-modules directory - these are IDE-specific and handled separately
575
- if (file.startsWith('sub-modules/')) {
576
- continue;
577
- }
578
-
579
- // Skip sidecar directories - these contain agent-specific assets not needed at install time
580
- const isInSidecarDirectory = path
581
- .dirname(file)
582
- .split('/')
583
- .some((dir) => dir.toLowerCase().endsWith('-sidecar'));
584
-
585
- if (isInSidecarDirectory) {
586
- continue;
587
- }
588
-
589
- // Skip module.yaml at root - it's only needed at install time
590
- if (file === 'module.yaml') {
591
- continue;
592
- }
593
-
594
- // Skip module root config.yaml only - generated by config collector with actual values
595
- // Workflow-level config.yaml (e.g. workflows/orchestrate-story/config.yaml) must be copied
596
- // for custom modules that use workflow-specific configuration
597
- if (file === 'config.yaml') {
598
- continue;
599
- }
600
-
601
- const sourceFile = path.join(sourcePath, file);
602
- const targetFile = path.join(targetPath, file);
603
-
604
- // Check if this is an agent file
605
- if (file.startsWith('agents/') && file.endsWith('.md')) {
606
- // Read the file to check for localskip
607
- const content = await fs.readFile(sourceFile, 'utf8');
608
-
609
- // Check for localskip="true" in the agent tag
610
- const agentMatch = content.match(/<agent[^>]*\slocalskip="true"[^>]*>/);
611
- if (agentMatch) {
612
- await prompts.log.message(` Skipping web-only agent: ${path.basename(file)}`);
613
- continue; // Skip this agent
614
- }
615
- }
616
-
617
- // Copy the file with placeholder replacement
618
- await this.copyFile(sourceFile, targetFile);
619
-
620
- // Track the file if callback provided
621
- if (fileTrackingCallback) {
622
- fileTrackingCallback(targetFile);
623
- }
624
- }
625
- }
626
-
627
- /**
628
- * Create directories declared in module.yaml's `directories` key
629
- * This replaces the security-risky module installer pattern with declarative config
630
- * During updates, if a directory path changed, moves the old directory to the new path
631
- * @param {string} moduleName - Name of the module
632
- * @param {string} wizzDir - Target wizz directory
633
- * @param {Object} options - Installation options
634
- * @param {Object} options.moduleConfig - Module configuration from config collector
635
- * @param {Object} options.existingModuleConfig - Previous module config (for detecting path changes during updates)
636
- * @param {Object} options.coreConfig - Core configuration
637
- * @returns {Promise<{createdDirs: string[], movedDirs: string[], createdWdsFolders: string[]}>} Created directories info
638
- */
639
- async createModuleDirectories(moduleName, wizzDir, options = {}) {
640
- const moduleConfig = options.moduleConfig || {};
641
- const existingModuleConfig = options.existingModuleConfig || {};
642
- const projectRoot = path.dirname(wizzDir);
643
- const emptyResult = { createdDirs: [], movedDirs: [], createdWdsFolders: [] };
644
-
645
- // Special handling for core module - it's in src/core-skills not src/modules
646
- let sourcePath;
647
- if (moduleName === 'core') {
648
- sourcePath = getSourcePath('core-skills');
649
- } else {
650
- sourcePath = await this.findModuleSource(moduleName, { silent: true });
651
- if (!sourcePath) {
652
- return emptyResult; // No source found, skip
653
- }
654
- }
655
-
656
- // Read module.yaml to find the `directories` key
657
- const moduleYamlPath = path.join(sourcePath, 'module.yaml');
658
- if (!(await fs.pathExists(moduleYamlPath))) {
659
- return emptyResult; // No module.yaml, skip
660
- }
661
-
662
- let moduleYaml;
663
- try {
664
- const yamlContent = await fs.readFile(moduleYamlPath, 'utf8');
665
- moduleYaml = yaml.parse(yamlContent);
666
- } catch (error) {
667
- await prompts.log.warn(`Invalid module.yaml for ${moduleName}: ${error.message}`);
668
- return emptyResult;
669
- }
670
-
671
- if (!moduleYaml || !moduleYaml.directories) {
672
- return emptyResult; // No directories declared, skip
673
- }
674
-
675
- const directories = moduleYaml.directories;
676
- const wdsFolders = moduleYaml.wds_folders || [];
677
- const createdDirs = [];
678
- const movedDirs = [];
679
- const createdWdsFolders = [];
680
-
681
- for (const dirRef of directories) {
682
- // Parse variable reference like "{design_artifacts}"
683
- const varMatch = dirRef.match(/^\{([^}]+)\}$/);
684
- if (!varMatch) {
685
- // Not a variable reference, skip
686
- continue;
687
- }
688
-
689
- const configKey = varMatch[1];
690
- const dirValue = moduleConfig[configKey];
691
- if (!dirValue || typeof dirValue !== 'string') {
692
- continue; // No value or not a string, skip
693
- }
694
-
695
- // Strip {project-root}/ prefix if present
696
- let dirPath = dirValue.replace(/^\{project-root\}\/?/, '');
697
-
698
- // Handle remaining {project-root} anywhere in the path
699
- dirPath = dirPath.replaceAll('{project-root}', '');
700
-
701
- // Resolve to absolute path
702
- const fullPath = path.join(projectRoot, dirPath);
703
-
704
- // Validate path is within project root (prevent directory traversal)
705
- const normalizedPath = path.normalize(fullPath);
706
- const normalizedRoot = path.normalize(projectRoot);
707
- if (!normalizedPath.startsWith(normalizedRoot + path.sep) && normalizedPath !== normalizedRoot) {
708
- const color = await prompts.getColor();
709
- await prompts.log.warn(color.yellow(`${configKey} path escapes project root, skipping: ${dirPath}`));
710
- continue;
711
- }
712
-
713
- // Check if directory path changed from previous config (update/modify scenario)
714
- const oldDirValue = existingModuleConfig[configKey];
715
- let oldFullPath = null;
716
- let oldDirPath = null;
717
- if (oldDirValue && typeof oldDirValue === 'string') {
718
- // F3: Normalize both values before comparing to avoid false negatives
719
- // from trailing slashes, separator differences, or prefix format variations
720
- let normalizedOld = oldDirValue.replace(/^\{project-root\}\/?/, '');
721
- normalizedOld = path.normalize(normalizedOld.replaceAll('{project-root}', ''));
722
- const normalizedNew = path.normalize(dirPath);
723
-
724
- if (normalizedOld !== normalizedNew) {
725
- oldDirPath = normalizedOld;
726
- oldFullPath = path.join(projectRoot, oldDirPath);
727
- const normalizedOldAbsolute = path.normalize(oldFullPath);
728
- if (!normalizedOldAbsolute.startsWith(normalizedRoot + path.sep) && normalizedOldAbsolute !== normalizedRoot) {
729
- oldFullPath = null; // Old path escapes project root, ignore it
730
- }
731
-
732
- // F13: Prevent parent/child move (e.g. docs/planning → docs/planning/v2)
733
- if (oldFullPath) {
734
- const normalizedNewAbsolute = path.normalize(fullPath);
735
- if (
736
- normalizedOldAbsolute.startsWith(normalizedNewAbsolute + path.sep) ||
737
- normalizedNewAbsolute.startsWith(normalizedOldAbsolute + path.sep)
738
- ) {
739
- const color = await prompts.getColor();
740
- await prompts.log.warn(
741
- color.yellow(
742
- `${configKey}: cannot move between parent/child paths (${oldDirPath} / ${dirPath}), creating new directory instead`,
743
- ),
744
- );
745
- oldFullPath = null;
746
- }
747
- }
748
- }
749
- }
750
-
751
- const dirName = configKey.replaceAll('_', ' ');
752
-
753
- if (oldFullPath && (await fs.pathExists(oldFullPath)) && !(await fs.pathExists(fullPath))) {
754
- // Path changed and old dir exists → move old to new location
755
- // F1: Use fs.move() instead of fs.rename() for cross-device/volume support
756
- // F2: Wrap in try/catch — fallback to creating new dir on failure
757
- try {
758
- await fs.ensureDir(path.dirname(fullPath));
759
- await fs.move(oldFullPath, fullPath);
760
- movedDirs.push(`${dirName}: ${oldDirPath} → ${dirPath}`);
761
- } catch (moveError) {
762
- const color = await prompts.getColor();
763
- await prompts.log.warn(
764
- color.yellow(
765
- `Failed to move ${oldDirPath} → ${dirPath}: ${moveError.message}\n Creating new directory instead. Please move contents from the old directory manually.`,
766
- ),
767
- );
768
- await fs.ensureDir(fullPath);
769
- createdDirs.push(`${dirName}: ${dirPath}`);
770
- }
771
- } else if (oldFullPath && (await fs.pathExists(oldFullPath)) && (await fs.pathExists(fullPath))) {
772
- // F5: Both old and new directories exist — warn user about potential orphaned documents
773
- const color = await prompts.getColor();
774
- await prompts.log.warn(
775
- color.yellow(
776
- `${dirName}: path changed but both directories exist:\n Old: ${oldDirPath}\n New: ${dirPath}\n Old directory may contain orphaned documents — please review and merge manually.`,
777
- ),
778
- );
779
- } else if (!(await fs.pathExists(fullPath))) {
780
- // New directory doesn't exist yet → create it
781
- createdDirs.push(`${dirName}: ${dirPath}`);
782
- await fs.ensureDir(fullPath);
783
- }
784
-
785
- // Create WDS subfolders if this is the design_artifacts directory
786
- if (configKey === 'design_artifacts' && wdsFolders.length > 0) {
787
- for (const subfolder of wdsFolders) {
788
- const subPath = path.join(fullPath, subfolder);
789
- if (!(await fs.pathExists(subPath))) {
790
- await fs.ensureDir(subPath);
791
- createdWdsFolders.push(subfolder);
792
- }
793
- }
794
- }
795
- }
796
-
797
- return { createdDirs, movedDirs, createdWdsFolders };
798
- }
799
-
800
- /**
801
- * Private: Sync module files (preserving user modifications)
802
- * @param {string} sourcePath - Source module path
803
- * @param {string} targetPath - Target module path
804
- */
805
- async syncModule(sourcePath, targetPath) {
806
- // Get list of all source files
807
- const sourceFiles = await this.getFileList(sourcePath);
808
-
809
- for (const file of sourceFiles) {
810
- const sourceFile = path.join(sourcePath, file);
811
- const targetFile = path.join(targetPath, file);
812
-
813
- // Check if target file exists and has been modified
814
- if (await fs.pathExists(targetFile)) {
815
- const sourceStats = await fs.stat(sourceFile);
816
- const targetStats = await fs.stat(targetFile);
817
-
818
- // Skip if target is newer (user modified)
819
- if (targetStats.mtime > sourceStats.mtime) {
820
- continue;
821
- }
822
- }
823
-
824
- // Copy file with placeholder replacement
825
- await this.copyFile(sourceFile, targetFile);
826
- }
151
+ return this.catalog.findModuleSource(moduleCode, options);
827
152
  }
828
153
 
829
154
  /**
@@ -833,88 +158,19 @@ class OfficialModules {
833
158
  * @returns {Array} List of relative file paths
834
159
  */
835
160
  async getFileList(dir, baseDir = dir) {
836
- const files = [];
837
- const entries = await fs.readdir(dir, { withFileTypes: true });
838
-
839
- for (const entry of entries) {
840
- const fullPath = path.join(dir, entry.name);
841
-
842
- if (entry.isDirectory()) {
843
- const subFiles = await this.getFileList(fullPath, baseDir);
844
- files.push(...subFiles);
845
- } else {
846
- files.push(path.relative(baseDir, fullPath));
847
- }
848
- }
849
-
850
- return files;
161
+ return this.catalog.getFileList(dir, baseDir);
851
162
  }
852
163
 
853
164
  // ─── Config collection methods (merged from ConfigCollector) ───
854
165
 
855
166
  /**
856
- * Find the wizz installation directory in a project
857
- * V6+ installations can use ANY folder name but ALWAYS have _config/manifest.yaml
167
+ * Find the wizz installation directory in a project.
168
+ * Delegated to ModuleCatalog (item 20, etapa 2).
858
169
  * @param {string} projectDir - Project directory
859
170
  * @returns {Promise<string>} Path to wizz directory
860
171
  */
861
172
  async findWizzDir(projectDir) {
862
- // Check if project directory exists
863
- if (!(await fs.pathExists(projectDir))) {
864
- // Project doesn't exist yet, return default
865
- return path.join(projectDir, 'wizz');
866
- }
867
-
868
- // V6+ strategy: Look for ANY directory with _config/manifest.yaml
869
- // This is the definitive marker of a V6+ installation
870
- try {
871
- const entries = await fs.readdir(projectDir, { withFileTypes: true });
872
- for (const entry of entries) {
873
- if (entry.isDirectory()) {
874
- const manifestPath = path.join(projectDir, entry.name, '_config', 'manifest.yaml');
875
- if (await fs.pathExists(manifestPath)) {
876
- // Found a V6+ installation
877
- return path.join(projectDir, entry.name);
878
- }
879
- }
880
- }
881
- } catch {
882
- // Ignore errors, fall through to default
883
- }
884
-
885
- // No V6+ installation found, return default
886
- // This will be used for new installations
887
- return path.join(projectDir, 'wizz');
888
- }
889
-
890
- /**
891
- * Detect the existing WIZZ folder name in a project
892
- * @param {string} projectDir - Project directory
893
- * @returns {Promise<string|null>} Folder name (just the name, not full path) or null if not found
894
- */
895
- async detectExistingWizzFolder(projectDir) {
896
- // Check if project directory exists
897
- if (!(await fs.pathExists(projectDir))) {
898
- return null;
899
- }
900
-
901
- // Look for ANY directory with _config/manifest.yaml
902
- try {
903
- const entries = await fs.readdir(projectDir, { withFileTypes: true });
904
- for (const entry of entries) {
905
- if (entry.isDirectory()) {
906
- const manifestPath = path.join(projectDir, entry.name, '_config', 'manifest.yaml');
907
- if (await fs.pathExists(manifestPath)) {
908
- // Found a V6+ installation, return just the folder name
909
- return entry.name;
910
- }
911
- }
912
- }
913
- } catch {
914
- // Ignore errors
915
- }
916
-
917
- return null;
173
+ return this.catalog.findWizzDir(projectDir);
918
174
  }
919
175
 
920
176
  /**
@@ -922,127 +178,18 @@ class OfficialModules {
922
178
  * @param {string} projectDir - Target project directory
923
179
  */
924
180
  async loadExistingConfig(projectDir) {
925
- this._existingConfig = {};
926
-
927
- // Check if project directory exists first
928
- if (!(await fs.pathExists(projectDir))) {
929
- return false;
930
- }
931
-
932
- // Find the actual wizz directory (handles custom folder names)
933
- const wizzDir = await this.findWizzDir(projectDir);
934
-
935
- // Check if wizz directory exists
936
- if (!(await fs.pathExists(wizzDir))) {
937
- return false;
938
- }
939
-
940
- // Primary source: installer-written config.toml + config.user.toml (v6+).
941
- // Both files together hold all install answers; config.user.toml carries
942
- // user-scoped keys like user_name that would otherwise be re-prompted on
943
- // every reinstall.
944
- let foundAny = false;
945
- for (const fileName of ['config.toml', 'config.user.toml']) {
946
- const tomlPath = path.join(wizzDir, fileName);
947
- if (!(await fs.pathExists(tomlPath))) continue;
948
- try {
949
- const content = await fs.readFile(tomlPath, 'utf8');
950
- const parsed = parseCentralToml(content);
951
- for (const [section, values] of Object.entries(parsed)) {
952
- if (values && typeof values === 'object' && !Array.isArray(values)) {
953
- if (!this._existingConfig[section]) this._existingConfig[section] = {};
954
- Object.assign(this._existingConfig[section], values);
955
- foundAny = true;
956
- }
957
- }
958
- } catch {
959
- // Ignore parse errors
960
- }
961
- }
962
-
963
- if (foundAny) {
964
- return true;
965
- }
966
-
967
- // Fallback: legacy per-module config.yaml files (pre-v6 installations).
968
- const entries = await fs.readdir(wizzDir, { withFileTypes: true });
969
- const nonModuleDirs = new Set(['_config', '_memory', 'memory', 'docs', 'scripts', 'custom']);
970
- for (const entry of entries) {
971
- if (entry.isDirectory()) {
972
- if (nonModuleDirs.has(entry.name)) {
973
- continue;
974
- }
975
-
976
- const moduleConfigPath = path.join(wizzDir, entry.name, 'config.yaml');
977
-
978
- if (await fs.pathExists(moduleConfigPath)) {
979
- try {
980
- const content = await fs.readFile(moduleConfigPath, 'utf8');
981
- const moduleConfig = yaml.parse(content);
982
- // Only keep plain object parses. A corrupt config.yaml that parses
983
- // to a scalar or array would crash later code that does `key in cfg`
984
- // / `Object.keys(cfg)`; treat it the same as a parse error.
985
- if (moduleConfig && typeof moduleConfig === 'object' && !Array.isArray(moduleConfig)) {
986
- this._existingConfig[entry.name] = moduleConfig;
987
- foundAny = true;
988
- }
989
- } catch {
990
- // Ignore parse errors for individual modules
991
- }
992
- }
993
- }
994
- }
995
-
996
- if (foundAny) {
997
- await this._hoistCoreKeysFromLegacyModuleConfigs();
998
- }
999
-
1000
- return foundAny;
181
+ // O catálogo é o dono do armazém; `_existingConfig` é um getter que lê
182
+ // dele, então não há snapshot para sincronizar aqui.
183
+ await this.catalog.loadExistingConfig(projectDir);
184
+ return this._existingConfig && Object.keys(this._existingConfig).length > 0;
1001
185
  }
1002
186
 
1003
187
  /**
1004
- * Migrate prior answers when a key has moved from a non-core module to core
1005
- * (e.g. project_name moving from bmm to core in #2279). Without this, the
1006
- * partition logic in writeCentralConfig drops the value from the bmm bucket
1007
- * (because it's now a core key) without re-homing it under [core], so the
1008
- * user's prior answer silently disappears on the next install/quick-update.
188
+ * Migrate prior answers when a key has moved from a non-core module to core.
189
+ * Delegated to ModuleCatalog (item 20, etapa 2).
1009
190
  */
1010
191
  async _hoistCoreKeysFromLegacyModuleConfigs() {
1011
- const coreSchemaPath = path.join(getSourcePath(), 'core-skills', 'module.yaml');
1012
- if (!(await fs.pathExists(coreSchemaPath))) return;
1013
-
1014
- let coreSchema;
1015
- try {
1016
- coreSchema = yaml.parse(await fs.readFile(coreSchemaPath, 'utf8'));
1017
- } catch {
1018
- return;
1019
- }
1020
- if (!coreSchema || typeof coreSchema !== 'object') return;
1021
-
1022
- const coreKeys = new Set(
1023
- Object.entries(coreSchema)
1024
- .filter(([, v]) => v && typeof v === 'object' && 'prompt' in v)
1025
- .map(([k]) => k),
1026
- );
1027
- if (coreKeys.size === 0) return;
1028
-
1029
- // Belt-and-suspenders: loadExistingConfig already filters non-object parses,
1030
- // but anyone calling _hoistCoreKeysFromLegacyModuleConfigs in isolation (or
1031
- // future code paths populating _existingConfig directly) shouldn't be able
1032
- // to crash this with a scalar / array.
1033
- const existingCore = this._existingConfig.core;
1034
- this._existingConfig.core = existingCore && typeof existingCore === 'object' && !Array.isArray(existingCore) ? existingCore : {};
1035
-
1036
- for (const [moduleName, cfg] of Object.entries(this._existingConfig)) {
1037
- if (moduleName === 'core' || !cfg || typeof cfg !== 'object' || Array.isArray(cfg)) continue;
1038
- for (const key of Object.keys(cfg)) {
1039
- if (!coreKeys.has(key)) continue;
1040
- if (!(key in this._existingConfig.core)) {
1041
- this._existingConfig.core[key] = cfg[key];
1042
- }
1043
- delete cfg[key];
1044
- }
1045
- }
192
+ await this.catalog._hoistCoreKeysFromLegacyModuleConfigs();
1046
193
  }
1047
194
 
1048
195
  /**
@@ -1052,1250 +199,29 @@ class OfficialModules {
1052
199
  * @returns {Promise<Array>} Array of {moduleName, displayName, questionCount, hasFieldsWithoutDefaults}
1053
200
  */
1054
201
  async scanModuleSchemas(modules) {
1055
- const metadataFields = new Set(['code', 'name', 'header', 'subheader', 'default_selected']);
1056
- const results = [];
1057
-
1058
- for (const moduleName of modules) {
1059
- // Resolve module.yaml path - standard location first, then OfficialModules search
1060
- let moduleConfigPath = null;
1061
- const standardPath = path.join(getModulePath(moduleName), 'module.yaml');
1062
- if (await fs.pathExists(standardPath)) {
1063
- moduleConfigPath = standardPath;
1064
- } else {
1065
- const moduleSourcePath = await this.findModuleSource(moduleName, { silent: true });
1066
- if (moduleSourcePath) {
1067
- moduleConfigPath = path.join(moduleSourcePath, 'module.yaml');
1068
- }
1069
- }
1070
-
1071
- if (!moduleConfigPath || !(await fs.pathExists(moduleConfigPath))) {
1072
- continue;
1073
- }
202
+ const results = await this.catalog.scanModuleSchemas(modules);
203
+ await this._flushCatalogLoadErrors();
204
+ return results;
205
+ }
206
+ }
1074
207
 
1075
- try {
1076
- const content = await fs.readFile(moduleConfigPath, 'utf8');
1077
- const moduleConfig = yaml.parse(content);
1078
- if (!moduleConfig) continue;
208
+ // Mixins do split do item 20 (etapa 3): o lado install mora em
209
+ // module-installer.js e a coleta interativa em config-collector.js. Montados
210
+ // no prototype para o estado continuar na mesma instância e o monkey-patching
211
+ // de métodos (dos callers e dos testes) continuar funcionando.
212
+ //
213
+ // Definidos como não-enumeráveis (como os métodos declarados em `class`), para
214
+ // que um `for...in` sobre uma instância não passe a listar os métodos vindos
215
+ // dos mixins.
216
+ function defineMixin(target, methods) {
217
+ const descriptors = {};
218
+ for (const [name, value] of Object.entries(methods)) {
219
+ descriptors[name] = { value, writable: true, enumerable: false, configurable: true };
220
+ }
221
+ Object.defineProperties(target, descriptors);
222
+ }
1079
223
 
1080
- const displayName = moduleConfig.header || `${moduleName.toUpperCase()} Module`;
1081
- const configKeys = Object.keys(moduleConfig).filter((key) => key !== 'prompt');
1082
- const questionKeys = configKeys.filter((key) => {
1083
- if (metadataFields.has(key)) return false;
1084
- const item = moduleConfig[key];
1085
- return item && typeof item === 'object' && item.prompt;
1086
- });
1087
-
1088
- const hasFieldsWithoutDefaults = questionKeys.some((key) => {
1089
- const item = moduleConfig[key];
1090
- return OfficialModules.isMissingDefault(item.default);
1091
- });
1092
-
1093
- results.push({
1094
- moduleName,
1095
- displayName,
1096
- questionCount: questionKeys.length,
1097
- hasFieldsWithoutDefaults,
1098
- });
1099
- } catch (error) {
1100
- await prompts.log.warn(`Could not read schema for module "${moduleName}": ${error.message}`);
1101
- }
1102
- }
1103
-
1104
- return results;
1105
- }
1106
-
1107
- /**
1108
- * Collect configuration for all modules
1109
- * @param {Array} modules - List of modules to configure (including 'core')
1110
- * @param {string} projectDir - Target project directory
1111
- * @param {Object} options - Additional options
1112
- * @param {boolean} options.skipPrompts - Skip prompts and use defaults (for --yes flag)
1113
- */
1114
- async collectAllConfigurations(modules, projectDir, options = {}) {
1115
- this.skipPrompts = options.skipPrompts || false;
1116
- this.modulesToCustomize = undefined;
1117
- await this.loadExistingConfig(projectDir);
1118
-
1119
- // Check if core was already collected (e.g., in early collection phase)
1120
- const coreAlreadyCollected = this.collectedConfig.core && Object.keys(this.collectedConfig.core).length > 0;
1121
-
1122
- // If core wasn't already collected, include it
1123
- const allModules = coreAlreadyCollected ? modules.filter((m) => m !== 'core') : ['core', ...modules.filter((m) => m !== 'core')];
1124
-
1125
- // Store all answers across modules for cross-referencing
1126
- if (!this.allAnswers) {
1127
- this.allAnswers = {};
1128
- }
1129
-
1130
- // Split processing: core first, then gateway, then remaining modules
1131
- const coreModules = allModules.filter((m) => m === 'core');
1132
- const nonCoreModules = allModules.filter((m) => m !== 'core');
1133
-
1134
- // Collect core config first (always fully prompted)
1135
- for (const moduleName of coreModules) {
1136
- await this.collectModuleConfig(moduleName, projectDir);
1137
- }
1138
-
1139
- // Show batch configuration gateway for non-core modules
1140
- // Scan all non-core module schemas for display names and config metadata
1141
- let scannedModules = [];
1142
- if (!this.skipPrompts && nonCoreModules.length > 0) {
1143
- scannedModules = await this.scanModuleSchemas(nonCoreModules);
1144
- const customizableModules = scannedModules.filter((m) => m.questionCount > 0);
1145
-
1146
- if (customizableModules.length > 0) {
1147
- const configMode = await prompts.select({
1148
- message: 'Module configuration',
1149
- choices: [
1150
- { name: 'Express Setup', value: 'express', hint: 'accept all defaults (recommended)' },
1151
- { name: 'Customize', value: 'customize', hint: 'choose modules to configure' },
1152
- ],
1153
- default: 'express',
1154
- });
1155
-
1156
- if (configMode === 'customize') {
1157
- const choices = customizableModules.map((m) => ({
1158
- name: `${m.displayName} (${m.questionCount} option${m.questionCount === 1 ? '' : 's'})`,
1159
- value: m.moduleName,
1160
- hint: m.hasFieldsWithoutDefaults ? 'has fields without defaults' : undefined,
1161
- checked: m.hasFieldsWithoutDefaults,
1162
- }));
1163
- const selected = await prompts.multiselect({
1164
- message: 'Select modules to customize:',
1165
- choices,
1166
- required: false,
1167
- });
1168
- this.modulesToCustomize = new Set(selected);
1169
- } else {
1170
- // Express mode: no modules to customize
1171
- this.modulesToCustomize = new Set();
1172
- }
1173
- } else {
1174
- // All non-core modules have zero config - no gateway needed
1175
- this.modulesToCustomize = new Set();
1176
- }
1177
- }
1178
-
1179
- // Collect remaining non-core modules
1180
- if (this.modulesToCustomize === undefined) {
1181
- // No gateway was shown (skipPrompts, no non-core modules, or direct call) - process all normally
1182
- for (const moduleName of nonCoreModules) {
1183
- await this.collectModuleConfig(moduleName, projectDir);
1184
- }
1185
- } else {
1186
- // Split into default modules (tasks progress) and customized modules (interactive)
1187
- const defaultModules = nonCoreModules.filter((m) => !this.modulesToCustomize.has(m));
1188
- const customizeModules = nonCoreModules.filter((m) => this.modulesToCustomize.has(m));
1189
-
1190
- // Run default modules with a single spinner
1191
- if (defaultModules.length > 0) {
1192
- // Build display name map from all scanned modules for pre-call spinner messages
1193
- const displayNameMap = new Map();
1194
- for (const m of scannedModules) {
1195
- displayNameMap.set(m.moduleName, m.displayName);
1196
- }
1197
-
1198
- const configSpinner = await prompts.spinner();
1199
- configSpinner.start('Configuring modules...');
1200
- try {
1201
- for (const moduleName of defaultModules) {
1202
- const displayName = displayNameMap.get(moduleName) || moduleName.toUpperCase();
1203
- configSpinner.message(`Configuring ${displayName}...`);
1204
- try {
1205
- this._silentConfig = true;
1206
- await this.collectModuleConfig(moduleName, projectDir);
1207
- } finally {
1208
- this._silentConfig = false;
1209
- }
1210
- }
1211
- } finally {
1212
- configSpinner.stop(customizeModules.length > 0 ? 'Module defaults applied' : 'Module configuration complete');
1213
- }
1214
- }
1215
-
1216
- // Run customized modules individually (may show interactive prompts)
1217
- for (const moduleName of customizeModules) {
1218
- await this.collectModuleConfig(moduleName, projectDir);
1219
- }
1220
-
1221
- if (customizeModules.length > 0) {
1222
- await prompts.log.step('Module configuration complete');
1223
- }
1224
- }
1225
-
1226
- // Add metadata
1227
- this.collectedConfig._meta = {
1228
- version: require(path.join(getProjectRoot(), 'package.json')).version,
1229
- installDate: new Date().toISOString(),
1230
- lastModified: new Date().toISOString(),
1231
- };
1232
-
1233
- return this.collectedConfig;
1234
- }
1235
-
1236
- /**
1237
- * Collect configuration for a single module (Quick Update mode - only new fields)
1238
- * @param {string} moduleName - Module name
1239
- * @param {string} projectDir - Target project directory
1240
- * @param {boolean} silentMode - If true, only prompt for new/missing fields
1241
- * @returns {boolean} True if new fields were prompted, false if all fields existed
1242
- */
1243
- async collectModuleConfigQuick(moduleName, projectDir, silentMode = true) {
1244
- this.currentProjectDir = projectDir;
1245
- // Load existing config if not already loaded
1246
- if (!this._existingConfig) {
1247
- await this.loadExistingConfig(projectDir);
1248
- }
1249
-
1250
- // Initialize allAnswers if not already initialized
1251
- if (!this.allAnswers) {
1252
- this.allAnswers = {};
1253
- }
1254
-
1255
- // Load module's config schema from module.yaml
1256
- // First, try the standard src/modules location
1257
- let moduleConfigPath = path.join(getModulePath(moduleName), 'module.yaml');
1258
-
1259
- // If not found in src/modules, we need to find it by searching the project
1260
- if (!(await fs.pathExists(moduleConfigPath))) {
1261
- const moduleSourcePath = await this.findModuleSource(moduleName, { silent: true });
1262
-
1263
- if (moduleSourcePath) {
1264
- moduleConfigPath = path.join(moduleSourcePath, 'module.yaml');
1265
- }
1266
- }
1267
-
1268
- if (!(await fs.pathExists(moduleConfigPath))) {
1269
- // No config schema for this module - use existing values
1270
- if (this._existingConfig && this._existingConfig[moduleName]) {
1271
- if (!this.collectedConfig[moduleName]) {
1272
- this.collectedConfig[moduleName] = {};
1273
- }
1274
- this.collectedConfig[moduleName] = { ...this._existingConfig[moduleName] };
1275
- }
1276
- return false;
1277
- }
1278
-
1279
- const configContent = await fs.readFile(moduleConfigPath, 'utf8');
1280
- const moduleConfig = yaml.parse(configContent);
1281
-
1282
- if (!moduleConfig) {
1283
- return false;
1284
- }
1285
-
1286
- // Compare schema with existing config to find new/missing fields
1287
- const configKeys = Object.keys(moduleConfig).filter((key) => key !== 'prompt');
1288
- const existingKeys = this._existingConfig && this._existingConfig[moduleName] ? Object.keys(this._existingConfig[moduleName]) : [];
1289
-
1290
- // Check if this module has no configuration keys at all (like CIS)
1291
- // Filter out metadata fields and only count actual config objects
1292
- const metadataFields = new Set(['code', 'name', 'header', 'subheader', 'default_selected']);
1293
- const actualConfigKeys = configKeys.filter((key) => !metadataFields.has(key));
1294
- const hasNoConfig = actualConfigKeys.length === 0;
1295
-
1296
- // If module has no config keys at all, handle it specially
1297
- if (hasNoConfig && moduleConfig.subheader) {
1298
- const moduleDisplayName = moduleConfig.header || `${moduleName.toUpperCase()} Module`;
1299
- await prompts.log.step(moduleDisplayName);
1300
- await prompts.log.message(` \u2713 ${moduleConfig.subheader}`);
1301
- return false; // No new fields
1302
- }
1303
-
1304
- // Find new interactive fields (with prompt)
1305
- const newKeys = configKeys.filter((key) => {
1306
- const item = moduleConfig[key];
1307
- // Check if it's a config item and doesn't exist in existing config
1308
- return item && typeof item === 'object' && item.prompt && !existingKeys.includes(key);
1309
- });
1310
-
1311
- // Find new static fields (without prompt, just result)
1312
- const newStaticKeys = configKeys.filter((key) => {
1313
- const item = moduleConfig[key];
1314
- return item && typeof item === 'object' && !item.prompt && item.result && !existingKeys.includes(key);
1315
- });
1316
-
1317
- // If in silent mode and no new keys (neither interactive nor static), use existing config and skip prompts
1318
- if (silentMode && newKeys.length === 0 && newStaticKeys.length === 0) {
1319
- if (this._existingConfig && this._existingConfig[moduleName]) {
1320
- if (!this.collectedConfig[moduleName]) {
1321
- this.collectedConfig[moduleName] = {};
1322
- }
1323
- this.collectedConfig[moduleName] = { ...this._existingConfig[moduleName] };
1324
-
1325
- // Special handling for user_name: ensure it has a value
1326
- if (
1327
- moduleName === 'core' &&
1328
- (!this.collectedConfig[moduleName].user_name || this.collectedConfig[moduleName].user_name === '[USER_NAME]')
1329
- ) {
1330
- this.collectedConfig[moduleName].user_name = this.getDefaultUsername();
1331
- }
1332
-
1333
- // Also populate allAnswers for cross-referencing
1334
- for (const [key, value] of Object.entries(this._existingConfig[moduleName])) {
1335
- // Ensure user_name is properly set in allAnswers too
1336
- let finalValue = value;
1337
- if (moduleName === 'core' && key === 'user_name' && (!value || value === '[USER_NAME]')) {
1338
- finalValue = this.getDefaultUsername();
1339
- }
1340
- this.allAnswers[`${moduleName}_${key}`] = finalValue;
1341
- }
1342
- } else if (moduleName === 'core') {
1343
- // No existing core config - ensure we at least have user_name
1344
- if (!this.collectedConfig[moduleName]) {
1345
- this.collectedConfig[moduleName] = {};
1346
- }
1347
- if (!this.collectedConfig[moduleName].user_name) {
1348
- this.collectedConfig[moduleName].user_name = this.getDefaultUsername();
1349
- this.allAnswers[`${moduleName}_user_name`] = this.getDefaultUsername();
1350
- }
1351
- }
1352
-
1353
- // Show "no config" message for modules with no new questions (that have config keys)
1354
- await prompts.log.message(` \u2713 ${moduleName.toUpperCase()} module already up to date`);
1355
- return false; // No new fields
1356
- }
1357
-
1358
- // If we have new fields (interactive or static), process them
1359
- if (newKeys.length > 0 || newStaticKeys.length > 0) {
1360
- const questions = [];
1361
- const staticAnswers = {};
1362
-
1363
- // Build questions for interactive fields
1364
- for (const key of newKeys) {
1365
- const item = moduleConfig[key];
1366
- const question = await this.buildQuestion(moduleName, key, item, moduleConfig);
1367
- if (question) {
1368
- questions.push(question);
1369
- }
1370
- }
1371
-
1372
- // Prepare static answers (no prompt, just result)
1373
- for (const key of newStaticKeys) {
1374
- staticAnswers[`${moduleName}_${key}`] = undefined;
1375
- }
1376
-
1377
- // Collect all answers (static + prompted)
1378
- let allAnswers = { ...staticAnswers };
1379
-
1380
- if (questions.length > 0 && silentMode) {
1381
- // In silent mode (quick update), use defaults for new fields instead of prompting
1382
- for (const q of questions) {
1383
- allAnswers[q.name] = typeof q.default === 'function' ? q.default({}) : q.default;
1384
- }
1385
- await prompts.log.message(` \u2713 ${moduleName.toUpperCase()} module configured with defaults`);
1386
- } else if (questions.length > 0) {
1387
- // Only show header if we actually have questions
1388
- await CLIUtils.displayModuleConfigHeader(moduleName, moduleConfig.header, moduleConfig.subheader);
1389
- await prompts.log.message('');
1390
- const promptedAnswers = await prompts.prompt(questions);
1391
-
1392
- // Merge prompted answers with static answers
1393
- Object.assign(allAnswers, promptedAnswers);
1394
- } else if (newStaticKeys.length > 0) {
1395
- // Only static fields, no questions - show no config message
1396
- await prompts.log.message(` \u2713 ${moduleName.toUpperCase()} module configuration updated`);
1397
- }
1398
-
1399
- // Store all answers for cross-referencing
1400
- Object.assign(this.allAnswers, allAnswers);
1401
-
1402
- // Process all answers (both static and prompted)
1403
- // First, copy existing config to preserve values that aren't being updated
1404
- if (this._existingConfig && this._existingConfig[moduleName]) {
1405
- this.collectedConfig[moduleName] = { ...this._existingConfig[moduleName] };
1406
- } else {
1407
- this.collectedConfig[moduleName] = {};
1408
- }
1409
-
1410
- for (const key of Object.keys(allAnswers)) {
1411
- const originalKey = key.replace(`${moduleName}_`, '');
1412
- const item = moduleConfig[originalKey];
1413
- const value = allAnswers[key];
1414
-
1415
- let result;
1416
- if (Array.isArray(value)) {
1417
- result = value;
1418
- } else if (item.result) {
1419
- result = this.processResultTemplate(item.result, value);
1420
- } else {
1421
- result = value;
1422
- }
1423
-
1424
- // Update the collected config with new/updated values
1425
- this.collectedConfig[moduleName][originalKey] = result;
1426
- }
1427
- }
1428
-
1429
- // Copy over existing values for fields that weren't prompted
1430
- if (this._existingConfig && this._existingConfig[moduleName]) {
1431
- if (!this.collectedConfig[moduleName]) {
1432
- this.collectedConfig[moduleName] = {};
1433
- }
1434
- for (const [key, value] of Object.entries(this._existingConfig[moduleName])) {
1435
- if (!this.collectedConfig[moduleName][key]) {
1436
- this.collectedConfig[moduleName][key] = value;
1437
- this.allAnswers[`${moduleName}_${key}`] = value;
1438
- }
1439
- }
1440
- }
1441
-
1442
- await this.displayModulePostConfigNotes(moduleName, moduleConfig);
1443
-
1444
- return newKeys.length > 0 || newStaticKeys.length > 0; // Return true if we had any new fields (interactive or static)
1445
- }
1446
-
1447
- /**
1448
- * Process a result template with value substitution
1449
- * @param {*} resultTemplate - The result template
1450
- * @param {*} value - The value to substitute
1451
- * @returns {*} Processed result
1452
- */
1453
- processResultTemplate(resultTemplate, value) {
1454
- let result = resultTemplate;
1455
-
1456
- if (typeof result === 'string' && value !== undefined) {
1457
- if (typeof value === 'string') {
1458
- result = result.replace('{value}', value);
1459
- } else if (typeof value === 'boolean' || typeof value === 'number') {
1460
- if (result === '{value}') {
1461
- result = value;
1462
- } else {
1463
- result = result.replace('{value}', value);
1464
- }
1465
- } else {
1466
- result = value;
1467
- }
1468
-
1469
- if (typeof result === 'string') {
1470
- result = result.replaceAll(/{([^}]+)}/g, (match, configKey) => {
1471
- if (configKey === 'project-root') {
1472
- return '{project-root}';
1473
- }
1474
- if (configKey === 'value') {
1475
- return match;
1476
- }
1477
-
1478
- let configValue = this.allAnswers[configKey] || this.allAnswers[`${configKey}`];
1479
- if (!configValue) {
1480
- for (const [answerKey, answerValue] of Object.entries(this.allAnswers)) {
1481
- if (answerKey.endsWith(`_${configKey}`)) {
1482
- configValue = answerValue;
1483
- break;
1484
- }
1485
- }
1486
- }
1487
-
1488
- if (!configValue) {
1489
- for (const mod of Object.keys(this.collectedConfig)) {
1490
- if (mod !== '_meta' && this.collectedConfig[mod] && this.collectedConfig[mod][configKey]) {
1491
- configValue = this.collectedConfig[mod][configKey];
1492
- if (typeof configValue === 'string' && configValue.includes('{project-root}/')) {
1493
- configValue = configValue.replace('{project-root}/', '');
1494
- }
1495
- break;
1496
- }
1497
- }
1498
- }
1499
-
1500
- return configValue || match;
1501
- });
1502
- }
1503
- }
1504
-
1505
- return result;
1506
- }
1507
-
1508
- /**
1509
- * Get the default username from the system
1510
- * @returns {string} Capitalized username\
1511
- */
1512
- getDefaultUsername() {
1513
- let result = 'Wizz';
1514
- try {
1515
- const os = require('node:os');
1516
- const userInfo = os.userInfo();
1517
- if (userInfo && userInfo.username) {
1518
- const username = userInfo.username;
1519
- result = username.charAt(0).toUpperCase() + username.slice(1);
1520
- }
1521
- } catch {
1522
- // Do nothing, just return 'Wizz'
1523
- }
1524
- return result;
1525
- }
1526
-
1527
- /**
1528
- * Collect configuration for a single module
1529
- * @param {string} moduleName - Module name
1530
- * @param {string} projectDir - Target project directory
1531
- * @param {boolean} skipLoadExisting - Skip loading existing config (for early core collection)
1532
- * @param {boolean} skipCompletion - Skip showing completion message (for early core collection)
1533
- */
1534
- async collectModuleConfig(moduleName, projectDir, skipLoadExisting = false, skipCompletion = false) {
1535
- this.currentProjectDir = projectDir;
1536
- // Load existing config if needed and not already loaded
1537
- if (!skipLoadExisting && !this._existingConfig) {
1538
- await this.loadExistingConfig(projectDir);
1539
- }
1540
-
1541
- // Initialize allAnswers if not already initialized
1542
- if (!this.allAnswers) {
1543
- this.allAnswers = {};
1544
- }
1545
- // Load module's config
1546
- let moduleConfigPath = path.join(getModulePath(moduleName), 'module.yaml');
1547
-
1548
- // If not found in src/modules or custom paths, search the project
1549
- if (!(await fs.pathExists(moduleConfigPath))) {
1550
- const moduleSourcePath = await this.findModuleSource(moduleName, { silent: true });
1551
-
1552
- if (moduleSourcePath) {
1553
- moduleConfigPath = path.join(moduleSourcePath, 'module.yaml');
1554
- }
1555
- }
1556
-
1557
- let configPath = null;
1558
- if (await fs.pathExists(moduleConfigPath)) {
1559
- configPath = moduleConfigPath;
1560
- } else {
1561
- // No config for this module
1562
- return;
1563
- }
1564
-
1565
- const configContent = await fs.readFile(configPath, 'utf8');
1566
- const moduleConfig = yaml.parse(configContent);
1567
-
1568
- if (!moduleConfig) {
1569
- return;
1570
- }
1571
-
1572
- // Process each config item
1573
- const questions = [];
1574
- const staticAnswers = {};
1575
- const configKeys = Object.keys(moduleConfig).filter((key) => key !== 'prompt');
1576
-
1577
- for (const key of configKeys) {
1578
- const item = moduleConfig[key];
1579
-
1580
- // Skip if not a config object
1581
- if (!item || typeof item !== 'object') {
1582
- continue;
1583
- }
1584
-
1585
- // Handle static values (no prompt, just result)
1586
- if (!item.prompt && item.result) {
1587
- // Add to static answers with a marker value
1588
- staticAnswers[`${moduleName}_${key}`] = undefined;
1589
- continue;
1590
- }
1591
-
1592
- // Handle interactive values (with prompt)
1593
- if (item.prompt) {
1594
- const question = await this.buildQuestion(moduleName, key, item, moduleConfig);
1595
- if (question) {
1596
- questions.push(question);
1597
- }
1598
- }
1599
- }
1600
-
1601
- // Collect all answers (static + prompted)
1602
- let allAnswers = { ...staticAnswers };
1603
-
1604
- // If there are questions to ask, prompt for accepting defaults vs customizing
1605
- if (questions.length > 0) {
1606
- const moduleDisplayName = moduleConfig.header || `${moduleName.toUpperCase()} Module`;
1607
-
1608
- // Skip prompts mode: use all defaults without asking
1609
- if (this.skipPrompts) {
1610
- await prompts.log.info(`Using default configuration for ${moduleDisplayName}`);
1611
- // Use defaults for all questions
1612
- for (const question of questions) {
1613
- const hasDefault = !OfficialModules.isMissingDefault(question.default);
1614
- if (hasDefault && typeof question.default !== 'function') {
1615
- allAnswers[question.name] = question.default;
1616
- }
1617
- }
1618
- } else {
1619
- if (!this._silentConfig) await prompts.log.step(`Configuring ${moduleDisplayName}`);
1620
- let useDefaults = true;
1621
- if (moduleName === 'core') {
1622
- useDefaults = false; // Core: always show all questions
1623
- } else if (this.modulesToCustomize === undefined) {
1624
- // Fallback: original per-module confirm (backward compat for direct calls)
1625
- const customizeAnswer = await prompts.prompt([
1626
- {
1627
- type: 'confirm',
1628
- name: 'customize',
1629
- message: 'Accept Defaults (no to customize)?',
1630
- default: true,
1631
- },
1632
- ]);
1633
- useDefaults = customizeAnswer.customize;
1634
- } else {
1635
- // Batch mode: use defaults unless module was selected for customization
1636
- useDefaults = !this.modulesToCustomize.has(moduleName);
1637
- }
1638
-
1639
- if (useDefaults && moduleName !== 'core') {
1640
- // Accept defaults - only ask questions that have NO default value
1641
- const questionsWithoutDefaults = questions.filter((q) => OfficialModules.isMissingDefault(q.default));
1642
-
1643
- if (questionsWithoutDefaults.length > 0) {
1644
- await prompts.log.message(` Asking required questions for ${moduleName.toUpperCase()}...`);
1645
- const promptedAnswers = await prompts.prompt(questionsWithoutDefaults);
1646
- Object.assign(allAnswers, promptedAnswers);
1647
- }
1648
-
1649
- // For questions with defaults that weren't asked, we need to process them with their default values
1650
- const questionsWithDefaults = questions.filter((q) => !OfficialModules.isMissingDefault(q.default));
1651
- for (const question of questionsWithDefaults) {
1652
- // Skip function defaults - these are dynamic and will be evaluated later
1653
- if (typeof question.default === 'function') {
1654
- continue;
1655
- }
1656
- allAnswers[question.name] = question.default;
1657
- }
1658
- } else {
1659
- const promptedAnswers = await prompts.prompt(questions);
1660
- Object.assign(allAnswers, promptedAnswers);
1661
- }
1662
- }
1663
- }
1664
-
1665
- // Store all answers for cross-referencing
1666
- Object.assign(this.allAnswers, allAnswers);
1667
-
1668
- // Process all answers (both static and prompted)
1669
- // Always process if we have any answers or static answers
1670
- if (Object.keys(allAnswers).length > 0 || Object.keys(staticAnswers).length > 0) {
1671
- const answers = allAnswers;
1672
-
1673
- // Process answers and build result values
1674
- for (const key of Object.keys(answers)) {
1675
- const originalKey = key.replace(`${moduleName}_`, '');
1676
- const item = moduleConfig[originalKey];
1677
- const value = answers[key];
1678
-
1679
- // Build the result using the template
1680
- let result;
1681
-
1682
- // For arrays (multi-select), handle differently
1683
- if (Array.isArray(value)) {
1684
- result = value;
1685
- } else if (item.result) {
1686
- result = item.result;
1687
-
1688
- // Replace placeholders only for strings
1689
- if (typeof result === 'string' && value !== undefined) {
1690
- // Replace {value} with the actual value
1691
- if (typeof value === 'string') {
1692
- result = result.replace('{value}', value);
1693
- } else if (typeof value === 'boolean' || typeof value === 'number') {
1694
- // For boolean and number values, if result is just "{value}", use the raw value
1695
- if (result === '{value}') {
1696
- result = value;
1697
- } else {
1698
- result = result.replace('{value}', value);
1699
- }
1700
- } else {
1701
- result = value;
1702
- }
1703
-
1704
- // Only do further replacements if result is still a string
1705
- if (typeof result === 'string') {
1706
- // Replace references to other config values
1707
- result = result.replaceAll(/{([^}]+)}/g, (match, configKey) => {
1708
- // Check if it's a special placeholder
1709
- if (configKey === 'project-root') {
1710
- return '{project-root}';
1711
- }
1712
-
1713
- // Skip if it's the 'value' placeholder we already handled
1714
- if (configKey === 'value') {
1715
- return match;
1716
- }
1717
-
1718
- // Look for the config value across all modules
1719
- // First check if it's in the current module's answers
1720
- let configValue = answers[`${moduleName}_${configKey}`];
1721
-
1722
- // Then check all answers (for cross-module references like outputFolder)
1723
- if (!configValue) {
1724
- // Try with various module prefixes
1725
- for (const [answerKey, answerValue] of Object.entries(this.allAnswers)) {
1726
- if (answerKey.endsWith(`_${configKey}`)) {
1727
- configValue = answerValue;
1728
- break;
1729
- }
1730
- }
1731
- }
1732
-
1733
- // Check in already collected config
1734
- if (!configValue) {
1735
- for (const mod of Object.keys(this.collectedConfig)) {
1736
- if (mod !== '_meta' && this.collectedConfig[mod] && this.collectedConfig[mod][configKey]) {
1737
- configValue = this.collectedConfig[mod][configKey];
1738
- break;
1739
- }
1740
- }
1741
- }
1742
-
1743
- return configValue || match;
1744
- });
1745
- }
1746
- }
1747
- } else {
1748
- result = value;
1749
- }
1750
-
1751
- // Store only the result value (no prompts, defaults, examples, etc.)
1752
- if (!this.collectedConfig[moduleName]) {
1753
- this.collectedConfig[moduleName] = {};
1754
- }
1755
- this.collectedConfig[moduleName][originalKey] = result;
1756
- }
1757
-
1758
- // No longer display completion boxes - keep output clean
1759
- } else {
1760
- // No questions for this module - show completion message with header if available
1761
- const moduleDisplayName = moduleConfig.header || `${moduleName.toUpperCase()} Module`;
1762
-
1763
- // Check if this module has NO configuration keys at all (like CIS)
1764
- // Filter out metadata fields and only count actual config objects
1765
- const metadataFields = new Set(['code', 'name', 'header', 'subheader', 'default_selected']);
1766
- const actualConfigKeys = configKeys.filter((key) => !metadataFields.has(key));
1767
- const hasNoConfig = actualConfigKeys.length === 0;
1768
-
1769
- if (!this._silentConfig) {
1770
- if (hasNoConfig && (moduleConfig.subheader || moduleConfig.header)) {
1771
- await prompts.log.step(moduleDisplayName);
1772
- if (moduleConfig.subheader) {
1773
- await prompts.log.message(` \u2713 ${moduleConfig.subheader}`);
1774
- } else {
1775
- await prompts.log.message(` \u2713 No custom configuration required`);
1776
- }
1777
- } else {
1778
- // Module has config but just no questions to ask
1779
- await prompts.log.message(` \u2713 ${moduleName.toUpperCase()} module configured`);
1780
- }
1781
- }
1782
- }
1783
-
1784
- // If we have no collected config for this module, but we have a module schema,
1785
- // ensure we have at least an empty object
1786
- if (!this.collectedConfig[moduleName]) {
1787
- this.collectedConfig[moduleName] = {};
1788
-
1789
- // If we accepted defaults and have no answers, we still need to check
1790
- // if there are any static values in the schema that should be applied
1791
- if (moduleConfig) {
1792
- for (const key of Object.keys(moduleConfig)) {
1793
- if (key !== 'prompt' && moduleConfig[key] && typeof moduleConfig[key] === 'object') {
1794
- const item = moduleConfig[key];
1795
- // For static items (no prompt, just result), apply the result
1796
- if (!item.prompt && item.result) {
1797
- // Apply any placeholder replacements to the result
1798
- let result = item.result;
1799
- if (typeof result === 'string') {
1800
- result = this.replacePlaceholders(result, moduleName, moduleConfig);
1801
- }
1802
- this.collectedConfig[moduleName][key] = result;
1803
- }
1804
- }
1805
- }
1806
- }
1807
- }
1808
-
1809
- await this.displayModulePostConfigNotes(moduleName, moduleConfig);
1810
- }
1811
-
1812
- /**
1813
- * Replace placeholders in a string with collected config values
1814
- * @param {string} str - String with placeholders
1815
- * @param {string} currentModule - Current module name (to look up defaults in same module)
1816
- * @param {Object} moduleConfig - Current module's config schema (to look up defaults)
1817
- * @returns {string} String with placeholders replaced
1818
- */
1819
- replacePlaceholders(str, currentModule = null, moduleConfig = null) {
1820
- if (typeof str !== 'string') {
1821
- return str;
1822
- }
1823
-
1824
- return str.replaceAll(/{([^}]+)}/g, (match, configKey) => {
1825
- // Preserve special placeholders
1826
- if (configKey === 'project-root' || configKey === 'value' || configKey === 'directory_name') {
1827
- return match;
1828
- }
1829
-
1830
- const configValue = this.resolveConfigValue(configKey, currentModule, moduleConfig);
1831
-
1832
- return configValue || match;
1833
- });
1834
- }
1835
-
1836
- /**
1837
- * Clean a stored path-like value for prompt display/input reuse.
1838
- * @param {*} value - Stored value
1839
- * @returns {*} Cleaned value
1840
- */
1841
- cleanPromptValue(value) {
1842
- if (typeof value === 'string' && value.startsWith('{project-root}/')) {
1843
- return value.replace('{project-root}/', '');
1844
- }
1845
-
1846
- return value;
1847
- }
1848
-
1849
- /**
1850
- * Resolve a config key from answers, collected config, existing config, or schema defaults.
1851
- * @param {string} configKey - Config key to resolve
1852
- * @param {string} currentModule - Current module name
1853
- * @param {Object} moduleConfig - Current module config schema
1854
- * @returns {*} Resolved value
1855
- */
1856
- resolveConfigValue(configKey, currentModule = null, moduleConfig = null) {
1857
- // Look for the config value in allAnswers (already answered questions)
1858
- let configValue = this.allAnswers?.[configKey] || this.allAnswers?.[`core_${configKey}`];
1859
-
1860
- if (!configValue && this.allAnswers) {
1861
- for (const [answerKey, answerValue] of Object.entries(this.allAnswers)) {
1862
- if (answerKey.endsWith(`_${configKey}`)) {
1863
- configValue = answerValue;
1864
- break;
1865
- }
1866
- }
1867
- }
1868
-
1869
- // Prefer the current module's persisted value when re-prompting an existing install
1870
- if (!configValue && currentModule && this._existingConfig?.[currentModule]?.[configKey] !== undefined) {
1871
- configValue = this._existingConfig[currentModule][configKey];
1872
- }
1873
-
1874
- // Check in already collected config
1875
- if (!configValue) {
1876
- for (const mod of Object.keys(this.collectedConfig)) {
1877
- if (mod !== '_meta' && this.collectedConfig[mod] && this.collectedConfig[mod][configKey]) {
1878
- configValue = this.collectedConfig[mod][configKey];
1879
- break;
1880
- }
1881
- }
1882
- }
1883
-
1884
- // Fall back to other existing module config values
1885
- if (!configValue && this._existingConfig) {
1886
- for (const mod of Object.keys(this._existingConfig)) {
1887
- if (mod !== '_meta' && this._existingConfig[mod] && this._existingConfig[mod][configKey]) {
1888
- configValue = this._existingConfig[mod][configKey];
1889
- break;
1890
- }
1891
- }
1892
- }
1893
-
1894
- // If still not found and we're in the same module, use the default from the config schema
1895
- if (!configValue && currentModule && moduleConfig && moduleConfig[configKey]) {
1896
- const referencedItem = moduleConfig[configKey];
1897
- if (referencedItem && referencedItem.default !== undefined) {
1898
- configValue = referencedItem.default;
1899
- }
1900
- }
1901
-
1902
- return this.cleanPromptValue(configValue);
1903
- }
1904
-
1905
- /**
1906
- * Convert an existing stored value back into the prompt-facing value for templated fields.
1907
- * For example, "{test_artifacts}/{value}" + "_wizz-output/test-artifacts/test-design"
1908
- * becomes "test-design" so the template is not applied twice on modify.
1909
- * @param {*} existingValue - Stored config value
1910
- * @param {string} moduleName - Module name
1911
- * @param {Object} item - Config item definition
1912
- * @param {Object} moduleConfig - Current module config schema
1913
- * @returns {*} Prompt-facing default value
1914
- */
1915
- normalizeExistingValueForPrompt(existingValue, moduleName, item, moduleConfig = null) {
1916
- const cleanedValue = this.cleanPromptValue(existingValue);
1917
-
1918
- if (typeof cleanedValue !== 'string' || typeof item?.result !== 'string' || !item.result.includes('{value}')) {
1919
- return cleanedValue;
1920
- }
1921
-
1922
- const [prefixTemplate = '', suffixTemplate = ''] = item.result.split('{value}');
1923
- const prefix = this.cleanPromptValue(this.replacePlaceholders(prefixTemplate, moduleName, moduleConfig));
1924
- const suffix = this.cleanPromptValue(this.replacePlaceholders(suffixTemplate, moduleName, moduleConfig));
1925
-
1926
- if ((prefix && !cleanedValue.startsWith(prefix)) || (suffix && !cleanedValue.endsWith(suffix))) {
1927
- return cleanedValue;
1928
- }
1929
-
1930
- const startIndex = prefix.length;
1931
- const endIndex = suffix ? cleanedValue.length - suffix.length : cleanedValue.length;
1932
- if (endIndex < startIndex) {
1933
- return cleanedValue;
1934
- }
1935
-
1936
- let promptValue = cleanedValue.slice(startIndex, endIndex);
1937
- if (promptValue.startsWith('/')) {
1938
- promptValue = promptValue.slice(1);
1939
- }
1940
- if (promptValue.endsWith('/')) {
1941
- promptValue = promptValue.slice(0, -1);
1942
- }
1943
-
1944
- return promptValue || cleanedValue;
1945
- }
1946
-
1947
- /**
1948
- * Build a prompt question from a config item
1949
- * @param {string} moduleName - Module name
1950
- * @param {string} key - Config key
1951
- * @param {Object} item - Config item definition
1952
- * @param {Object} moduleConfig - Full module config schema (for resolving defaults)
1953
- */
1954
- async buildQuestion(moduleName, key, item, moduleConfig = null) {
1955
- const questionName = `${moduleName}_${key}`;
1956
-
1957
- // Check for existing value
1958
- let existingValue = null;
1959
- if (this._existingConfig && this._existingConfig[moduleName]) {
1960
- existingValue = this._existingConfig[moduleName][key];
1961
- existingValue = this.normalizeExistingValueForPrompt(existingValue, moduleName, item, moduleConfig);
1962
- }
1963
-
1964
- // Special handling for user_name: default to system user
1965
- if (moduleName === 'core' && key === 'user_name' && !existingValue) {
1966
- item.default = this.getDefaultUsername();
1967
- }
1968
-
1969
- // Determine question type and default value
1970
- let questionType = 'input';
1971
- let defaultValue = item.default;
1972
- let choices = null;
1973
-
1974
- // Check if default contains references to other fields in the same module
1975
- const hasSameModuleReference = typeof defaultValue === 'string' && defaultValue.match(/{([^}]+)}/);
1976
- let dynamicDefault = false;
1977
-
1978
- // Replace placeholders in default value with collected config values
1979
- if (typeof defaultValue === 'string') {
1980
- if (defaultValue.includes('{directory_name}') && this.currentProjectDir) {
1981
- const dirName = path.basename(this.currentProjectDir);
1982
- defaultValue = defaultValue.replaceAll('{directory_name}', dirName);
1983
- }
1984
-
1985
- // Check if this references another field in the same module (for dynamic defaults)
1986
- if (hasSameModuleReference && moduleConfig) {
1987
- const matches = defaultValue.match(/{([^}]+)}/g);
1988
- if (matches) {
1989
- for (const match of matches) {
1990
- const fieldName = match.slice(1, -1); // Remove { }
1991
- // Check if this field exists in the same module config
1992
- if (moduleConfig[fieldName]) {
1993
- dynamicDefault = true;
1994
- break;
1995
- }
1996
- }
1997
- }
1998
- }
1999
-
2000
- // If not dynamic, replace placeholders now
2001
- if (!dynamicDefault) {
2002
- defaultValue = this.replacePlaceholders(defaultValue, moduleName, moduleConfig);
2003
- }
2004
-
2005
- // Strip {project-root}/ from defaults since it will be added back by result template
2006
- // This makes the display cleaner and user input simpler
2007
- if (defaultValue.includes('{project-root}/')) {
2008
- defaultValue = defaultValue.replace('{project-root}/', '');
2009
- }
2010
- }
2011
-
2012
- // Handle different question types
2013
- if (item['single-select']) {
2014
- questionType = 'list';
2015
- choices = item['single-select'].map((choice) => {
2016
- // If choice is an object with label and value
2017
- if (typeof choice === 'object' && choice.label && choice.value !== undefined) {
2018
- return {
2019
- name: choice.label,
2020
- value: choice.value,
2021
- };
2022
- }
2023
- // Otherwise it's a simple string choice
2024
- return {
2025
- name: choice,
2026
- value: choice,
2027
- };
2028
- });
2029
- if (existingValue) {
2030
- defaultValue = existingValue;
2031
- }
2032
- } else if (item['multi-select']) {
2033
- questionType = 'checkbox';
2034
- choices = item['multi-select'].map((choice) => {
2035
- // If choice is an object with label and value
2036
- if (typeof choice === 'object' && choice.label && choice.value !== undefined) {
2037
- return {
2038
- name: choice.label,
2039
- value: choice.value,
2040
- checked: existingValue
2041
- ? existingValue.includes(choice.value)
2042
- : item.default && Array.isArray(item.default)
2043
- ? item.default.includes(choice.value)
2044
- : false,
2045
- };
2046
- }
2047
- // Otherwise it's a simple string choice
2048
- return {
2049
- name: choice,
2050
- value: choice,
2051
- checked: existingValue
2052
- ? existingValue.includes(choice)
2053
- : item.default && Array.isArray(item.default)
2054
- ? item.default.includes(choice)
2055
- : false,
2056
- };
2057
- });
2058
- } else if (typeof defaultValue === 'boolean') {
2059
- questionType = 'confirm';
2060
- }
2061
-
2062
- // Build the prompt message
2063
- let message = '';
2064
-
2065
- // Handle array prompts for multi-line messages
2066
- if (Array.isArray(item.prompt)) {
2067
- message = item.prompt.join('\n');
2068
- } else {
2069
- message = item.prompt;
2070
- }
2071
-
2072
- // Replace placeholders in prompt message with collected config values
2073
- if (typeof message === 'string') {
2074
- message = this.replacePlaceholders(message, moduleName, moduleConfig);
2075
- }
2076
-
2077
- // Add current value indicator for existing configs
2078
- const color = await prompts.getColor();
2079
- if (existingValue !== null && existingValue !== undefined) {
2080
- if (typeof existingValue === 'boolean') {
2081
- message += color.dim(` (current: ${existingValue ? 'true' : 'false'})`);
2082
- } else if (Array.isArray(existingValue)) {
2083
- message += color.dim(` (current: ${existingValue.join(', ')})`);
2084
- } else if (questionType !== 'list') {
2085
- // Show the cleaned value (without {project-root}/) for display
2086
- message += color.dim(` (current: ${existingValue})`);
2087
- }
2088
- } else if (item.example && questionType === 'input') {
2089
- // Show example for input fields
2090
- let exampleText = typeof item.example === 'string' ? item.example : JSON.stringify(item.example);
2091
- // Replace placeholders in example
2092
- if (typeof exampleText === 'string') {
2093
- exampleText = this.replacePlaceholders(exampleText, moduleName, moduleConfig);
2094
- exampleText = exampleText.replace('{project-root}/', '');
2095
- }
2096
- message += color.dim(` (e.g., ${exampleText})`);
2097
- }
2098
-
2099
- // Build the question object
2100
- const question = {
2101
- type: questionType,
2102
- name: questionName,
2103
- message: message,
2104
- };
2105
-
2106
- // Set default - if it's dynamic, use a function that the prompt will evaluate with current answers
2107
- // But if we have an existing value, always use that instead
2108
- if (existingValue !== null && existingValue !== undefined && questionType !== 'list') {
2109
- question.default = existingValue;
2110
- } else if (dynamicDefault && typeof item.default === 'string') {
2111
- const originalDefault = item.default;
2112
- question.default = (answers) => {
2113
- // Replace placeholders using answers from previous questions in the same batch
2114
- let resolved = originalDefault;
2115
- resolved = resolved.replaceAll(/{([^}]+)}/g, (match, fieldName) => {
2116
- // Look for the answer in the current batch (prefixed with module name)
2117
- const answerKey = `${moduleName}_${fieldName}`;
2118
- if (answers[answerKey] !== undefined) {
2119
- return answers[answerKey];
2120
- }
2121
- // Fall back to collected config
2122
- return this.collectedConfig[moduleName]?.[fieldName] || match;
2123
- });
2124
- // Strip {project-root}/ for cleaner display
2125
- if (resolved.includes('{project-root}/')) {
2126
- resolved = resolved.replace('{project-root}/', '');
2127
- }
2128
- return resolved;
2129
- };
2130
- } else {
2131
- question.default = defaultValue;
2132
- }
2133
-
2134
- // Add choices for select types
2135
- if (choices) {
2136
- question.choices = choices;
2137
- }
2138
-
2139
- // Add validation for input fields
2140
- if (questionType === 'input') {
2141
- question.validate = (input) => {
2142
- if (!input && item.required) {
2143
- return 'This field is required';
2144
- }
2145
- // Validate against regex pattern if provided
2146
- if (input && item.regex) {
2147
- const regex = new RegExp(item.regex);
2148
- if (!regex.test(input)) {
2149
- return `Invalid format. Must match pattern: ${item.regex}`;
2150
- }
2151
- }
2152
- return true;
2153
- };
2154
- }
2155
-
2156
- // Add validation for checkbox (multi-select) fields
2157
- if (questionType === 'checkbox' && item.required) {
2158
- question.validate = (answers) => {
2159
- if (!answers || answers.length === 0) {
2160
- return 'At least one option must be selected';
2161
- }
2162
- return true;
2163
- };
2164
- }
2165
-
2166
- return question;
2167
- }
2168
-
2169
- /**
2170
- * Display post-configuration notes for a module
2171
- * Shows prerequisite guidance based on collected config values
2172
- * Reads notes from the module's `post-install-notes` section in module.yaml
2173
- * Supports two formats:
2174
- * - Simple string: always displayed
2175
- * - Object keyed by config field name, with value-specific messages
2176
- * @param {string} moduleName - Module name
2177
- * @param {Object} moduleConfig - Parsed module.yaml content
2178
- */
2179
- async displayModulePostConfigNotes(moduleName, moduleConfig) {
2180
- if (this._silentConfig) return;
2181
- if (!moduleConfig || !moduleConfig['post-install-notes']) return;
2182
-
2183
- const notes = moduleConfig['post-install-notes'];
2184
- const color = await prompts.getColor();
2185
-
2186
- // Format 1: Simple string - always display
2187
- if (typeof notes === 'string') {
2188
- await prompts.log.message('');
2189
- for (const line of notes.trim().split('\n')) {
2190
- await prompts.log.message(color.dim(line));
2191
- }
2192
- return;
2193
- }
2194
-
2195
- // Format 2: Conditional on config values
2196
- if (typeof notes === 'object') {
2197
- const config = this.collectedConfig[moduleName];
2198
- if (!config) return;
2199
-
2200
- let hasOutput = false;
2201
- for (const [configKey, valueMessages] of Object.entries(notes)) {
2202
- const selectedValue = config[configKey];
2203
- if (!selectedValue || !valueMessages[selectedValue]) continue;
2204
-
2205
- if (hasOutput) await prompts.log.message('');
2206
- hasOutput = true;
2207
-
2208
- const message = valueMessages[selectedValue];
2209
- for (const line of message.trim().split('\n')) {
2210
- const trimmedLine = line.trim();
2211
- if (trimmedLine.endsWith(':') && !trimmedLine.startsWith(' ')) {
2212
- await prompts.log.info(color.bold(trimmedLine));
2213
- } else {
2214
- await prompts.log.message(color.dim(' ' + trimmedLine));
2215
- }
2216
- }
2217
- }
2218
- }
2219
- }
2220
-
2221
- /**
2222
- * Deep merge two objects
2223
- * @param {Object} target - Target object
2224
- * @param {Object} source - Source object
2225
- */
2226
- deepMerge(target, source) {
2227
- const result = { ...target };
2228
-
2229
- for (const key in source) {
2230
- if (source[key] && typeof source[key] === 'object' && !Array.isArray(source[key])) {
2231
- if (result[key] && typeof result[key] === 'object' && !Array.isArray(result[key])) {
2232
- result[key] = this.deepMerge(result[key], source[key]);
2233
- } else {
2234
- result[key] = source[key];
2235
- }
2236
- } else {
2237
- result[key] = source[key];
2238
- }
2239
- }
2240
-
2241
- return result;
2242
- }
2243
- }
2244
-
2245
- /**
2246
- * Parse a config.toml or config.user.toml written by writeCentralConfig.
2247
- * Only handles the subset of TOML the installer produces: [core],
2248
- * [modules.<code>], string/bool/number scalar values. [agents.*] and other
2249
- * sections are ignored. Returns a plain object keyed by section name where
2250
- * module sections use the bare code (e.g. "bmm"), not the full "modules.bmm".
2251
- */
2252
- function parseCentralToml(content) {
2253
- const result = {};
2254
- let currentSection = null;
2255
-
2256
- for (const rawLine of content.split('\n')) {
2257
- const line = rawLine.trim();
2258
- if (!line || line.startsWith('#')) continue;
2259
-
2260
- const sectionMatch = line.match(/^\[([^\]]+)\]\s*$/);
2261
- if (sectionMatch) {
2262
- const name = sectionMatch[1];
2263
- if (name === 'core') {
2264
- currentSection = 'core';
2265
- } else if (name.startsWith('modules.')) {
2266
- currentSection = name.slice('modules.'.length);
2267
- } else {
2268
- currentSection = null;
2269
- }
2270
- if (currentSection && !result[currentSection]) {
2271
- result[currentSection] = {};
2272
- }
2273
- continue;
2274
- }
2275
-
2276
- if (!currentSection) continue;
2277
-
2278
- const kvMatch = line.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\s*=\s*(.+)$/);
2279
- if (!kvMatch) continue;
2280
-
2281
- const key = kvMatch[1];
2282
- const raw = kvMatch[2].trim();
2283
- let value;
2284
- if (raw.startsWith('"') && raw.endsWith('"')) {
2285
- value = raw.slice(1, -1).replaceAll(/\\(["\\nrbt])/g, (_, c) => ({ '"': '"', '\\': '\\', n: '\n', r: '\r', b: '\b', t: '\t' })[c]);
2286
- } else if (raw === 'true') {
2287
- value = true;
2288
- } else if (raw === 'false') {
2289
- value = false;
2290
- } else if (raw !== '' && !isNaN(raw)) {
2291
- value = Number(raw);
2292
- } else {
2293
- value = raw;
2294
- }
2295
- result[currentSection][key] = value;
2296
- }
2297
-
2298
- return result;
2299
- }
224
+ defineMixin(OfficialModules.prototype, ModuleInstallerMethods);
225
+ defineMixin(OfficialModules.prototype, ConfigCollectorMethods);
2300
226
 
2301
227
  module.exports = { OfficialModules };